开发者

How to update a property using Type.GetProperties() method?

I've a collection of a class' properties and would like to update each one's value by iterating over the collection through the index.

1) I create the collection of properties this way

private PropertyInfo[] GetPropertiesOfMyClass()
    {
        Type myType = (typeof(myClass));
        PropertyInfo[] PropertyInfoArray = myType.GetProperties(
                       开发者_如何学Go                         BindingFlags.Public |
                                                BindingFlags.Instance);
        return PropertyInfoArray;                 
    }

2)Now, I'd like to set up the value of each one depending on the index this way

    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
    }

I'd like to be able to call UpdateProperty from a Controller like this:

UpdateProperty(instanceOfMyClass, valueToUpdate, indexOfTheProperty);

Honestly, I do not know how to involve the instanceOfMyClass in the game as GetProperty only plays with myClass.

Since I saw that I can use Name, PropertyType, ... to get information on the property. So, I've tried also GetPropertyOfMyClass()[index].SetValue(...), but I was lost in the arguments of its constructor, so I abandoned.

What I want is to be able to update the value of a property in my collection just by using the index.

Thanks for helping


Your guess was correct. You use SetValue() to update the value - this is how to do it:

GetPropertyOfMyClass()[index].SetValue( instanceOfMyClass, valueToUpdate, null);

The last argument can be null:

Optional index values for indexed properties. This value should be null for non-indexed properties.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜