简体   繁体   中英

How to pass the current instance to FieldInfo.GetValue inside the instance?

I'm making an abstract class that I need to validate fields in it's descendants. All the validated fields are marked by an attribute and are suppose to be checked for nulls or empty. To do that I get all the fields in the class:

var fields = this.GetType().GetFields().Where(field => Attribute.IsDefined(field, typeof(MyAttribute))).ToList(); 

And then, for every FieldInfo I try to do this:

if (string.IsNullOrEmpty(field.GetValue(this).ToString()))
{
    // write down the name of the field
}

I get a System.NullReferenceException: object reference not set to an instance of an object .

I know I am suppose to pass the instance of a class to the GetValue method. But how can I pass the current instance (the one that's launching the logic)?

Or: Is there an other way of getting the field's value?

The GetValue call is fine. The problem lies in the return value on which you're calling ToString .

If GetValue returns null , then ToString will be called on this null value, and this will throw the NullReferenceException .

Do something like this instead:

var value = field.GetValue(this);
if (value == null || string.IsNullOrEmpty(value.ToString()))
{
    // write down the name of the field
}

As Lucas says, the problem will be calling ToString() when you shouldn't. Presumably your attribute should only be applied to string fields anyway, so the simplest approach is just to cast the result to string . If that cast fails, it indicates a bigger bug (the attribute being applied incorrectly).

if (string.IsNullOrEmpty((string) field.GetValue(this)))

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