通过使用不同属性类型的reflection设置对象的属性

我使用reflection来填充对象的属性。

这些属性有不同的类型:String,Nullable(double)和Nullable(long)(不知道如何在这里转义尖括号……)。 这些属性的值来自(字符串,对象)对的字典。

因此,例如我的类具有以下属性:

string Description { get; set; } Nullable Id { get; set; } Nullable 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)) { info.SetValue(this, Convert.ToDouble(thisPropertyValue), null); } else if (propertyType == typeof(Nullable)) { 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); } } 

谢谢,斯特凡诺

如果值已经是正确的类型,那么否:您不必做任何事情。 如果它们可能不对(int vs float等),一个简单的方法可能是:

编辑调整为空)

 Type propertyType = info.PropertyType; if (thisPropertyValue != null) { Type underlyingType = Nullable.GetUnderlyingType(propertyType); thisPropertyValue = Convert.ChangeType( thisPropertyValue, underlyingType ?? propertyType); } info.SetValue(this, thisPropertyValue, null);