Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用PropertyInfo[]循环并为类属性赋值_C#_Reflection - Fatal编程技术网

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

C# 使用PropertyInfo[]循环并为类属性赋值,c#,reflection,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 prop

我正在尝试使用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]);
        }
    }
}

我得到一个错误,说“对象与目标类型不匹配”。在看到堆栈或其他消息板上的其他示例后,我确定我缺少了什么

我已经创建了一个名为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);
            }
        }
    }
}
公共静态类扩展
{
公共静态void convertNullToString(此T clsObject),其中T:class
{
PropertyInfo[]properties=clsObject.GetType().GetProperties();
foreach(属性中的var信息)
{
//如果字符串为空,则设置为string.Empty
if(info.PropertyType==typeof(string)和&info.GetValue(clsObject,null)==null)
{
info.SetValue(clsObject,String.Empty,null);
}
}
}
}

我会将该代码转换为静态方法,我会发布一个示例,说明我在做什么,以及如何调用它,而不管类名如何,这样您就不必像在代码中那样硬编码
typeoc(Car)
。谢谢。我会试一试的。@GoodBoyNYC这应该对你有用,只要做一两个改动。。基本上,您可以通过创建一个类来测试这一点。。然后调用代码,当您创建一个类的新实例时,它基本上会更改所有类的auto属性。如果为null,它们的默认属性将设置为string.Empty。我希望这是有道理的。。