使用 PropertyInfo[] 循环遍历类属性并将其赋值给类属性

本文关键字:属性 赋值 PropertyInfo 循环 遍历 使用 | 更新日期: 2023-09-27 18:34:08

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

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 或其他留言板上看到其他一些示例后我错过了什么。

使用 PropertyInfo[] 循环遍历类属性并将其赋值给类属性

我创建了一个名为扩展的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);
            }
        }
    }
}