简体   繁体   中英

PropertyInfo.GetValue returned object is not seen as null by visual studio / resharper

I'm retrieving the value of a property by calling the GetValue like so:

//have T tObj;
var sExpr = s.Body as MemberExpression;
var sProp = typeof(T).GetProperty(sExpr.Member.Name);
var sVal = dProp.GetValue(tObj, null);

For some reason sVal is never considered to be null by the compiler/resharper (i'm not sure which one is showing the warning). I don't get possible null reference warnings at design time. If I create a condition like if(sVal == null) I'll get a design time warning that the expression is always false.

sVal is just an object, and objects can be null. I don't think GetValue guarantees never to return null. What's going on?

John Skeet was right. I was checking for null after working with the variable. I rearranged my code to do the null check BEFORE working with the variable and the problem went away. What strange is that I didn't get a null reference warning before and I should have.

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