【发布时间】:2010-10-26 03:43:21
【问题描述】:
我正在使用反射来填充对象的属性。
这些属性有不同的类型:String、Nullable(double) 和 Nullable(long)(这里不知道如何转义尖括号...)。这些属性的值来自(字符串,对象)对的字典。
因此,例如,我的班级具有以下属性:
string Description { get; set; }
Nullable<long> Id { get; set; }
Nullable<double> MaxPower { get; set; }
(实际上大约有十几个属性)并且字典将包含 , ,
等条目现在我使用类似以下的方法来设置值:
foreach (PropertyInfo info in this.GetType().GetProperties())
{
if (info.CanRead)
{
object thisPropertyValue = dictionary[info.Name];
if (thisPropertyValue != null && info.CanWrite)
{
Type propertyType = info.PropertyType;
if (propertyType == typeof(String))
{
info.SetValue(this, Convert.ToString(thisPropertyValue), null);
}
else if (propertyType == typeof(Nullable<double>))
{
info.SetValue(this, Convert.ToDouble(thisPropertyValue), null);
}
else if (propertyType == typeof(Nullable<long>))
{
info.SetValue(this, Convert.ToInt64(thisPropertyValue), null);
}
else
{
throw new ApplicationException("Unexpected property type");
}
}
}
}
所以问题是:我真的必须在分配值之前检查每个属性的类型吗?有没有什么类似于我可以执行的强制转换,以便为属性值分配相应属性的类型?
理想情况下,我希望能够做一些类似的事情(我天真地认为这可能有效):
if (thisPropertyValue != null && info.CanWrite)
{
Type propertyType = info.PropertyType;
if (propertyType == typeof(String))
{
info.SetValue(this, (propertyType)thisPropertyValue, null);
}
}
谢谢, 斯特凡诺
【问题讨论】:
标签: c# reflection properties runtime