通过嵌套类不能访问外部类的非静态成员

问题描述:

我有误差

无法访问Project.Neuro外类型的非静态成员通过
  嵌套式Project.Neuro.Net

Cannot access a non-static member of outer type 'Project.Neuro' via nested type 'Project.Neuro.Net'

与code像这样(简体):

with code like this (simplified):

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类,但我需要外界的这种方法。

I can move problematic method to Neuro.Net class, but I need this method outside.

林样的目标规划新手。

先谢谢了。

问题是,嵌套的类不是的导出的类,所以在外部类中的方法不是的继承

The problem is that nested classes are not derived classes, so the methods in the outer class are not inherited.

某些选项


  1. 请方法静态

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

    public static int OtherMethod() 
    {
        return 123;  
    }
}


  • 使用继承代替嵌套类:

  • Use inheritance instead of nesting classes:

    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(); 
        }
    }
    


  • 创建神经的一个实例:

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