【发布时间】:2011-08-20 17:44:07
【问题描述】:
在 C# 中,问题时常会出现。通常我得到一个对象值,然后我必须为它调用“真实”函数。像这样的:
if (type==typeof(byte))
val = rs.GetByte(col);
else if (type==typeof(int))
val = rs.GetInt32(col);
...
或
if (type==typeof(byte))
Call((byte)val);
else if (type==typeof(int))
Call((int)val);
...
我可以在这里看到一个文本模式,但我没有想出一个可以一次性解决所有脏活的解决方案。
你如何处理它?你收到对象值,你必须设置它或传递它,但不是作为对象,而是作为具体类型(POD,可空的 POD 和字符串)和。 ..?
编辑
完整的示例(这个是问题的原因):
protected IRecord ReadRecord()
{
if (!ResultSet.Read())
return null;
IRecord record = CreateIRecord();
var type = record.GetType();
int column = -1;
foreach (var prop in type.GetProperties())
{
++column;
object val;
if (prop.PropertyType == typeof(byte))
val = ResultSet.GetByte(column);
else if (prop.PropertyType == typeof(byte?))
val = ResultSet.GetSqlByte(column).ToNullable();
else if (prop.PropertyType == typeof(int))
val = ResultSet.GetInt32(column);
else if (prop.PropertyType == typeof(int?))
val = ResultSet.GetSqlInt32(column).ToNullable();
else if (prop.PropertyType == typeof(double))
val = ResultSet.GetDouble(column);
else if (prop.PropertyType == typeof(double?))
val = ResultSet.GetSqlDouble(column).ToNullable();
else if (prop.PropertyType == typeof(DateTime))
val = ResultSet.GetDateTime(column);
else if (prop.PropertyType == typeof(DateTime?))
val = ResultSet.GetSqlDateTime(column).ToNullable();
else if (prop.PropertyType == typeof(string))
val = ResultSet.GetString(column);
else
throw new ArgumentException("Invalid property type {0}".Expand(prop.PropertyType.ToString()));
prop.SetValue(record, val, null);
}
return record;
}
【问题讨论】:
-
你需要有更完整的示例代码;事实上,
type和rs和col是什么尚不清楚,它们之间的关系(或缺乏关系)也不清楚。 -
@Mr E 这并不总是可行的,尤其是在处理简单类型或不同的对象层次结构时
标签: c# object types switch-statement