如何使用Type.GetProperties()方法更新属性?

Ric*_*d77 1 c#-3.0

我有一个类的属性的集合,并希望通过索引迭代集合来更新每个属性的值.

1)我以这种方式创建属性集合

private PropertyInfo[] GetPropertiesOfMyClass()
    {
        Type myType = (typeof(myClass));
        PropertyInfo[] PropertyInfoArray = myType.GetProperties(
                                                BindingFlags.Public |
                                                BindingFlags.Instance);
        return PropertyInfoArray;                 
    }
Run Code Online (Sandbox Code Playgroud)

2)现在,我想通过这种方式根据索引设置每个值

    public void UpdateProperty(MyClass instanceOfMyClass, string valueToUpdate, int index)
    {
      //TODO:
      //1. Get an individual property from the GetPropertyOfMyClass() using index
      //2. Update the value of an individual property of the instanceOfMyClass
    }
Run Code Online (Sandbox Code Playgroud)

我希望能够从Controller中调用UpdateProperty,如下所示:

UpdateProperty(instanceOfMyClass, valueToUpdate, indexOfTheProperty);
Run Code Online (Sandbox Code Playgroud)

老实说,我不知道如何在游戏中涉及instanceOfMyClass,因为GetProperty只能与myClass一起玩.

因为我看到我可以使用Name,PropertyType,...来获取有关该属性的信息.所以,我也尝试过GetPropertyOfMyClass()[index] .SetValue(...),但是我在构造函数的参数中迷失了,所以我放弃了.

我想要的是只需使用索引就可以更新集合中属性的值.

谢谢你的帮助

tan*_*ius 5

你的猜测是正确的.您SetValue()用来更新值 - 这是如何做到的:

GetPropertyOfMyClass()[index].SetValue( instanceOfMyClass, valueToUpdate, null);
Run Code Online (Sandbox Code Playgroud)

最后一个参数可以为null:

索引属性的可选索引值.对于非索引属性,此值应为null.