简体   繁体   中英

"Object reference not set to an instance of an object" when exposing an expression-bodied method .NET 7

I have wrote the code snippet on do.netfiddle.net with compiler settings set to .NET 7

using System;

public class Person
    {
        private string fname;
        private string lname;
        private int ide = 30;
        public Person(string fN, string lN)
        {
            fname = fN;
            lname = lN;
        }
        public bool ID() => GetType().GetProperty("ide").GetValue(this, null).Equals(30);
    }

public class Program
{
    public static void Main()
    {
        Person p = new Person("Mandy", "Dejesus");
        p.ID();
    }
}

I have checked others questions who have received the same warning and they seem to suggest creating an object with the new keyword. I've done that yet I still get the error. What am I doing wrong?

I expect true but I'm currently getting

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object 
   at Person.ID()
   at Program.Main() 

You are getting a NullReferenceException because you are executing GetValue on a null . The reason is as follows:

In this line:

GetType().GetProperty("ide").GetValue(this, null).Equals(30);

The first part GetType() returns the Type of your Person class. Then you execute GetProperty("ide") on it, but ide is not a property, it's a field. Therefore GetProperty() returns null and executing GetValue throws the NullReferenceException .

One potential solution is to make ide an actual property instead of a field:

private int ide {get; set;}

Note: You might want to call it Ide instead, but then rename it in the GetProperty parameter.

This should fix your issue, but as others have said in the comments, you might want to refactor the code to achieve the same result in a much cleaner way.

Your ID function makes no sense and seems to call a bunch of functions that don't exist or aren't necessary.

Here is the correct function.

public bool ID() {
     return this.ide == 30;
}

Let's assume you wanted to keep using Reflection. What would you actually need to do?

Francesc Castells has the right explanation for where the NRE comes from. To fix the code essentually you'd need to change out GetProperty() for GetField() .

However, that's not good enough, because ide is a private field. So you need to tell Reflection to include searching for private fields as well.

using System.Reflection;

// ...

public bool ID() => GetType().GetField("ide", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this).Equals(30);

Still not very pretty. Go with the right way .

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