【问题标题】:Setting properties of an object through reflection with different properties types使用不同的属性类型通过反射设置对象的属性
【发布时间】: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


    【解决方案1】:

    如果值已经是正确的类型,则不:您无需执行任何操作。如果它们可能不正确(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);
    

    【讨论】:

    • 我打算建议尝试一下 info.SetValue(this, thisPropertyValue, null);但这似乎是一个更好的解决方案。
    • +1 表示 Convert.ChangeType 方法。这是避免代码中的 if 的绝佳解决方案。
    • @Marc:谢谢,这成功了 ;) @ChrisF: info.SetValue(this, thisPropertyValue, null) 在我的一个测试用例中尝试从 int 转换为 double 时引发异常.
    • @Stefano - 这只是一个建议;)
    最近更新 更多