.NET 7中表达式体方法触发空引用异常问题排查
问题:反射获取私有字段时触发空引用异常
我在dotnetfiddle.net上编写了以下代码片段,编译器设置为.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(); } }
我预期返回true,但实际得到:
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object at Person.ID() at Program.Main()
我查阅了遇到相同错误的其他问题,它们建议使用new关键字创建对象,我已这么做但仍报错。我哪里出错了?
问题原因与修复方案
- 错误根源:你用
GetType().GetProperty("ide")尝试获取名为ide的属性,但ide是私有字段,不是属性。GetProperty找不到对应的属性,返回null,后续调用GetValue就触发了空引用异常。 - 修复方案:
- 用反射获取私有字段:使用
GetField方法,并指定BindingFlags.NonPublic | BindingFlags.Instance来访问私有实例字段,修正后的代码如下:using System; using System.Reflection; 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() => (int)GetType().GetField("ide", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this) == 30; } public class Program { public static void Main() { Person p = new Person("Mandy", "Dejesus"); Console.WriteLine(p.ID()); // 输出 true } } - 直接访问字段(无需反射):如果不需要用反射的场景,直接访问私有字段更简单高效,避免反射的额外开销和错误:
public bool ID() => ide == 30;
- 用反射获取私有字段:使用
内容的提问来源于stack exchange,提问作者feddy
相关产品推荐
相关产品推荐

