通过与不同的属性类型的反射设定对象的属性 [英] Setting properties of an object through reflection with different properties types
问题描述
我使用反射来填充对象的属性。
I am using reflection to populate the properties of an object.
这些属性有不同的类型:字符串,可空(双)和可空(长)(不知道如何逃离这里尖括号......)。 。这些属性的值是从(字符串,对象)对的字典来
These properties have different types: String, Nullable(double) and Nullable(long) (don't know how to escape the angle brackets here ...). The values for these properties are coming from a dictionary of (string, object) pairs.
因此,例如我的类具有以下属性:
So, for example my class has the following properties:
string Description { get; set; }
Nullable<long> Id { get; set; }
Nullable<double> MaxPower { get; set; }
(现实中有十几属性)和字典将有条目类似<说明,说明><ID,123456>,<牛魔王,20000>
(in reality there are about a dozen properties) and the dictionary will have entries like <"Description", "A description">, <"Id", 123456>, <"MaxPower", 20000>
现在我使用类似以下内容设置的值:
Now I am using something like the following to set the values:
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");
}
}
}
}
所以,问题是:我真的有指定的值之前,检查每个属性的类型?有没有像投什么我可以执行,这样属性值分配相应属性的类型?
So the question is: do I really have to check the type of each property before assigning the value? Is there anything like a cast that I can perform so that the property value is assigned the type of the corresponding property?
在理想情况下,我想能做点什么像的以下(这是我天真地以为本来是可行的):
Ideally I would like to be able to do something like the following (which I naively thought might have worked):
if (thisPropertyValue != null && info.CanWrite)
{
Type propertyType = info.PropertyType;
if (propertyType == typeof(String))
{
info.SetValue(this, (propertyType)thisPropertyValue, null);
}
}
谢谢,
斯特凡诺
Thanks, Stefano
推荐答案
如果该值已正确类型的,则没有:你没有做任何事情。如果他们可能不适合(INT VS浮点等),在一个简单的方法可能是:
If the values are already of the correct type, then no: you don't have to do anything. If they might not be right (int vs float, etc), the a simple approach might be:
(修改空值调整)
Type propertyType = info.PropertyType;
if (thisPropertyValue != null)
{
Type underlyingType = Nullable.GetUnderlyingType(propertyType);
thisPropertyValue = Convert.ChangeType(
thisPropertyValue, underlyingType ?? propertyType);
}
info.SetValue(this, thisPropertyValue, null);
这篇关于通过与不同的属性类型的反射设定对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!