C# 如何使用 MethodInfo.Invoke 设置属性值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1067312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use MethodInfo.Invoke to set property value?
提问by David.Chu.ca
I have a class with a property Value like this:
我有一个类的属性值是这样的:
public class MyClass {
public property var Value { get; set; }
....
}
I want to use MethodInfo.Invoke() to set property value. Here are some codes:
我想使用 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?
I cannot access to my work VS right now. My question is how to set Value with a integer value such as 23?
我现在无法访问我的工作 VS。我的问题是如何使用整数值(例如 23)设置 Value?
采纳答案by CMS
You can use the PropertyInfo.SetValuemethod.
您可以使用PropertyInfo.SetValue方法。
object o;
//...
Type type = o.GetType();
PropertyInfo pi = type.GetProperty("Value");
pi.SetValue(o, 23, null);
回答by Thomas
If you are using .NET Framework 4.6 and 4.5, you can also use PropertyInfo.SetMethod Property:
如果您使用.NET Framework 4.6 和 4.5,您还可以使用PropertyInfo.SetMethod 属性:
object o;
//...
Type type = o.GetType();
PropertyInfo pi = type.GetProperty("Value");
pi.SetMethod.Invoke(o, new object[] {23});