如何使用MethodInfo.Invoke设置属性值?

时间:2009-07-01 04:46:54

标签: c# reflection

我有一个具有如下属性值的类:

public class MyClass {
   public property var Value { get; set; }
   ....
}

我想使用MethodInfo.Invoke()来设置属性值。以下是一些代码:

object o;
// use CodeDom to get instance of a dynamically built MyClass to o, codes omitted
Type type = o.GetType();
MethodInfo mi = type.GetProperty("Value");
mi.Invoke(o, new object[] {23}); // Set Value to 23?

我现在无法访问我的作品VS.我的问题是如何使用整数值设置值,例如23?

3 个答案:

答案 0 :(得分:13)

您可以使用PropertyInfo.SetValue方法。

object o;
//...
Type type = o.GetType();
PropertyInfo pi = type.GetProperty("Value");
pi.SetValue(o, 23, null);

答案 1 :(得分:3)

如果您使用的是 .NET Framework 4.6和4.5 ,则还可以使用PropertyInfo.SetMethod Property

object o;
//...
Type type = o.GetType();
PropertyInfo pi = type.GetProperty("Value");
pi.SetMethod.Invoke(o, new object[] {23});

答案 2 :(得分:0)

您可以使用System.Reflection命名空间中的PropertyInfo类来执行此操作。