我有一个具有如下属性值的类:
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?
答案 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
类来执行此操作。