繁体   English   中英

公开表达式体方法时“对象引用未设置到对象的实例” .NET 7

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

我在 do.netfiddle.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();
    }
}

我检查了收到相同警告的其他问题,他们似乎建议使用 new 关键字创建一个 object。 我已经这样做了,但我仍然收到错误。 我究竟做错了什么?

我希望是true ,但我目前正在

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

您将收到 NullReferenceException,因为您正在null上执行GetValue 原因如下:

在这一行中:

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

第一部分GetType()返回您的Person class 的Type 。然后您对其执行GetProperty("ide") ,但ide不是属性,它是一个字段。 因此GetProperty()返回null并执行GetValue抛出NullReferenceException

一种可能的解决方案是使ide成为实际财产而不是字段:

private int ide {get; set;}

注意:您可能想改为调用它Ide ,但随后在 GetProperty 参数中将其重命名。

这应该可以解决您的问题,但正如其他人在评论中所说,您可能希望重构代码以更简洁的方式实现相同的结果。

您的 ID function 毫无意义,似乎调用了一堆不存在或不必要的函数。

这是正确的 function。

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

假设您继续使用 Reflection。 你实际上需要做什么?

Francesc Castells对 NRE 的来源有正确的解释。 要从根本上修复代码,您需要将GetProperty()更改为GetField()

但是,这还不够好,因为ide私有字段。 因此,您需要告诉 Reflection 也包括搜索私有字段。

using System.Reflection;

// ...

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

仍然不是很漂亮。 Go 配正道

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM