循环并使用PropertyInfo []为类属性赋值

时间:2016-02-10 17:06:05

标签: c# reflection

我正在尝试使用propertyinfo数组自动将字符串数组中的字符串值分配给类属性。

Class Car
{
    public string wheels, doors, windows;
    PropertyInfo[] props = typeof(Car).GetProperties();
    public Car(string[] values)
    {
        int index=0;
        foreach(PropertyInfo pi in props)
        {
            pi.SetValue(pi.Name, values[index], null);
            //pi.SetValue(pi.Name, values[index]);
        }
    }
}

我收到错误消息“对象与目标类型不匹配”。在Stack或其他留言板上看到其他一些示例后,我确定我所缺少的内容。

1 个答案:

答案 0 :(得分:2)

我创建了一个名为Extensions的public static class Extensions,我已将此代码放入您应该能够非常轻松地遵循代码

public static class Extensions
{
    public static void ConvertNullToStringEmpty<T>(this T clsObject) where T : class
    {
        PropertyInfo[] properties = clsObject.GetType().GetProperties();
        foreach (var info in properties)
        {
            // if a string and null, set to String.Empty
            if (info.PropertyType == typeof(string) && info.GetValue(clsObject, null) == null)
            {
                info.SetValue(clsObject, String.Empty, null);
            }
        }
    }
}