8

我有错误

无法通过嵌套类型“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 类,但我需要在外面使用这个方法。

我是一种客观的编程新手。

提前致谢。

4

4 回答 4

22

问题是嵌套类不是派生类,所以外部类中的方法不是继承的。

一些选项是

  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;  
        }
    }
    
于 2013-05-01T15:23:16.693 回答
2

您需要Neuro在代码中的某处实例化一个类型的对象并调用OtherMethod它,因为OtherMethod它不是静态方法。无论您是在 内部创建此对象SomeMethod,还是将其作为参数传递给它,都取决于您。就像是:

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

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

或者,您可以OtherMethod将其设为静态,这样您就可以SomeMethod像现在一样调用它。

于 2013-05-01T15:20:02.073 回答
0

我认为在内部类中创建外部类的实例不是一个好的选择,因为您可以在外部类构造函数上执行业务逻辑。制作静态方法或属性是更好的选择。如果您坚持创建外部类的实例,那么您应该向外部类构造函数添加另一个参数以不执行业务逻辑。

于 2014-07-17T12:10:41.337 回答
0

即使类嵌套在另一个类中,外部类的哪个实例与内部类的哪个实例对话仍然不明显。我可以创建内部类的实例并将其传递给外部类的另一个实例。因此,您需要特定的实例来调用 this 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;  
    }
}
于 2013-05-01T15:23:33.697 回答