简体   繁体   中英

PropertyInfo.GetValue(null) - how it should behave?

I'm writing a compare properties two objects of some class, for further listing differences.

Class oldObj, newObj;
//some initiation of above

Class classObject = new Class();
var objectKeys = classObject .GetType().GetProperties().ToList();
objectKeys.ForEach(key => {
    var previousKeyValue = key.GetValue(oldObj);
    var newKeyValue = key.GetValue(newObj);
    if (!Equals) {...}
});

In special cases, newObj or oldObj can be nulls.

My problem is that, in such a case: key.GetValue(null) I'm getting CS0120 exception - "Non-static method requires a target".

Looking at PropertyInfo options (from metadata):

public object? GetValue(object? obj);

I assumed that it will be able to handle such a situation with object being null , with eg return null as its value.

Could you please explain if this is proper behaviour of this code, or I'm making something wrong to use null? In such a case I would probably just before ForEach make some verification if objects are nulls and write separate compare code, handling this situation.

You are misunderstanding the nature of the parameter that is passed to GetValue() .

When you pass in an object reference, it means that the reference is an instance property on an instance of an object. If you omit the object reference, you are telling the reflection api that you are trying to access a static member.

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