簡體   English   中英

無法通過嵌套類型訪問外部類型的非靜態成員

[英]Cannot access a non-static member of outer type via nested type

我有錯誤

無法通過嵌套類型“Project.Neuro.Net”訪問外部類型“Project.Neuro”的非靜態成員

使用這樣的代碼(簡化):

class Neuro
{
    public class Net
    {
        public void SomeMethod()
        {
            int x = OtherMethod(); // error is here
        }
    }

    public int OtherMethod() // its outside Neuro.Net class
    {
        return 123;  
    }
}

我可以將有問題的方法移到Neuro.Net類,但我需要在外面使用這個方法。

我是一種客觀的編程新手。

提前致謝。

問題是嵌套類不是派生類,因此外部類中的方法不會被繼承

有些選擇

  1. 使方法static

     class Neuro { public class Net { public void SomeMethod() { int x = Neuro.OtherMethod(); } } public static int OtherMethod() { return 123; } } 
  2. 使用繼承而不是嵌套類:

     public class Neuro // Neuro has to be public in order to have a public class inherit from it. { public static int OtherMethod() { return 123; } } public class Net : Neuro { public void SomeMethod() { int x = OtherMethod(); } } 
  3. 創建一個Neuro實例:

     class Neuro { public class Net { public void SomeMethod() { Neuro n = new Neuro(); int x = n.OtherMethod(); } } public int OtherMethod() { return 123; } } 

你需要在代碼中的某個地方實例化一個Neuro類型的對象,並在其上調用OtherMethod ,因為OtherMethod不是靜態方法。 是否在SomeMethod創建此對象,或將其作為參數傳遞給它取決於您。 就像是:

// somewhere in the code
var neuroObject = new Neuro();

// inside SomeMethod()
int x = neuroObject.OtherMethod();

或者,您可以將OtherMethod靜態,這樣您就可以OtherMethod現在一樣從SomeMethod調用它。

盡管類嵌套在另一個類中,但外部類的哪個實例與哪個內部類實例進行對話仍然不明顯。 我可以創建一個內部類的實例,並將其傳遞給外部類的另一個實例。 因此,您需要特定的實例來調用此OtherMethod()

您可以在創建時傳遞實例:

class Neuro
{
    public class Net
    {
        private Neuro _parent;
        public Net(Neuro parent)
        {
         _parent = parent;
        }
        public void SomeMethod()
        {
            _parent.OtherMethod(); 
        }
    }

    public int OtherMethod() 
    {
        return 123;  
    }
}

我認為在內部類中創建外部類的實例不是一個好的選擇,因為您可以在外部類構造函數上執行業務邏輯。 制作靜態方法或屬性是更好的選擇。 如果您堅持創建外部類的實例,則應該向外部類構造器添加另一個不執行業務邏輯的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM