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

Dav*_*.ca 7 c# reflection

我有一个具有属性Value的类,如下所示:

public class MyClass {
   public property var Value { get; set; }
   ....
}
Run Code Online (Sandbox Code Playgroud)

我想使用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?
Run Code Online (Sandbox Code Playgroud)

我现在无法访问我的工作.我的问题是如何使用23等整数值设置Value?

CMS*_*CMS 13

您可以使用PropertyInfo.SetValue方法.

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