簡體   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