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

C# 如何使用MethodInfo.Invoke设置属性值?,c#,reflection,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(); Metho

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

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)设置值?

您可以使用该方法


如果您正在使用.NET Framework 4.6和4.5,还可以使用:


实际上它应该是:pi.SetValue(o,23,null)?不使用PropertyInfo.SetValue,如下所述。如果您发现必须使用MethodInfo对象,请获取属性的“get”方法(PropertyInfo.getMethod()),并如上所述调用它。
object o;
//...
Type type = o.GetType();
PropertyInfo pi = type.GetProperty("Value");
pi.SetValue(o, 23, null);
object o;
//...
Type type = o.GetType();
PropertyInfo pi = type.GetProperty("Value");
pi.SetMethod.Invoke(o, new object[] {23});