2009-07-01 122 views
6

我有这样的属性值类:如何使用MethodInfo.Invoke设置属性值?

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? 

我现在无法访问我的工作。我的问题是如何设置一个整数值,如23值?

+0

使用PropertyInfo.SetValue,如下所述。如果您发现您受限于使用MethodInfo对象,请获取该属性的“get”方法(PropertyInfo.GetGetMethod()),并如上所述调用它。 – 2009-07-01 06:06:39

回答

13

您可以使用PropertyInfo.SetValue方法。

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

实际上它应该是:pi.SetValue(o,23,null); ?不是0 – 2009-07-01 05:03:27

2

如果您正在使用的.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});