简体   繁体   中英

.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. 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.

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.

That being said, I suspect you want the property of the sender instance instead:

PropertyInfo propInfo = sender.GetType().GetProperty("PropName");
String propName = propInfo.GetValue(sender, null).ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM