简体   繁体   中英

Avoid null reference warnings when dynamically accessing properties of object using reflection in C#

I am trying to dynamically access properties of an object by using reflection:

class Program
{
    private class MyClass
    {
        public int prop1 { get; set; } = 1;
        public int prop2 { get; set; } = 2;
    }

    public static void Main()
    {
        var obj = new MyClass();

        var propList = new List<string> { "prop1", "prop2"};

        foreach (string propString in propList) 
        {
            var prop = obj.GetType().GetProperty(propString);
            // I get a compiler warning here: "Dereference of a possibly null reference."
            Console.WriteLine((int)prop.GetValue(obj));
        }
    }
}

I would like to prevent the "null reference" warning in an appropriate way.

I have tried adding a if (prop == null) return; check before the Console.WriteLine , but that doesn't clear up the issue. Instead it turns the warning to "Unboxing a possibly null value".

Is there a way to enforce that the strings in propList are names of properties in MyClass? In that case, I would be comfortable silencing the warning with a. since I would know that the property would always exist, In my mind this would be ideal. because then I would get a compiler error when creating the list.

Looks like it's not just the prop that may be null, but also the value returned by prop.GetValue(obj) .

Try

var prop = obj.GetType().GetProperty(propString);
if (prop == null) return;
var o = prop.GetValue(obj);
if (o == null) return;
Console.WriteLine((int)o);

Or equivalent.

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