[英].NET Reflection PropInfo.GetValue() in a static context
I am stuck with a weird problem 我遇到了一个奇怪的问题
Let me show you my code 让我告诉你我的代码
private static void OnMyCustomPropertyChanged(Object sender, EventArgs e)
{
PropertyInfo propInfo = e.GetType().GetProperty("PropName");
String propName = propInfo.GetValue(?,?).ToString();
}
The problem is, what do I mention in place of the two question marks, the second parameter is null as far as I know since it is not an indexed property. 问题是,我提到代替两个问号,第二个参数是null,据我所知,因为它不是索引属性。 When I use propInfo/propInfo.GetType().GetProperty("PropName")/sender, in place of the first "?", I am getting an exception - TargetException was unhandled by user code. 当我使用propInfo / propInfo.GetType()。GetProperty(“PropName”)/ sender,代替第一个“?”时,我得到一个异常 - TargetException未被用户代码处理。
I was wondering if anyone could help me out with this along with an explanation if possible. 我想知道是否有人可以帮我解决这个问题以及可能的解释。 I would like to understand where I am making the mistake. 我想知道我在哪里弄错了。
The first parameter must be the instance you want to get the value from. 第一个参数必须是要从中获取值的实例。
In your example, you should pass e
as parameter, because you're getting a property of the e
object. 在您的示例中,您应该将e
作为参数传递,因为您正在获取e
对象的属性。
That being said, I suspect you want the property of the sender
instance instead: 话虽这么说,我怀疑你想要sender
实例的属性:
PropertyInfo propInfo = sender.GetType().GetProperty("PropName");
String propName = propInfo.GetValue(sender, null).ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.