2013-05-01 74 views
8

我有错误无法通过嵌套类型访问外类型的非静态成员

不能访问外类型的非静态成员“Project.Neuro”经由 嵌套类型“Project.Neuro.Net '

与这样的代码(简化):

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

似乎很明显 - 'OtherMethod'是另一种类型的成员。它嵌套的事实并不意味着这些方法是_inherited_。 – 2013-05-01 15:19:06

+1

看到这个答案的更多信息:http://stackoverflow.com/a/5393472/1451531 – Splendor 2013-05-01 15:21:31

回答

16

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

某些选项

  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; 
        } 
    } 
    
+0

我让我的方法是静态的。现在我想知道我应该如何重新组织我的班级......也许是另一个问题的好主题。 – Kamil 2013-05-01 15:44:22

2

您需要实例Neuro类型某处的对象在你的代码,并呼吁它OtherMethod,因为OtherMethod不是一个静态方法。无论您在SomeMethod之内创建此对象,还是将其作为参数传递给您,都取决于您。喜欢的东西:

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

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

或者,您也可以使OtherMethod静态的,这将让你从SomeMethod称其为您当前所在。

+0

好的。谢谢。现在我想我应该重新组织我的代码... – Kamil 2013-05-01 15:24:57

+0

我希望我能接受2个答案... – Kamil 2013-05-01 15:32:33

+0

@Kamil不用担心,D斯坦利的答案无论如何都是比较完整的。 – vlad 2013-05-01 15:33:06

0

即使类嵌套在另一个类中,它仍然是不明显的内部类的哪个哪个的外部类实例的会谈情况。我可以创建一个内部类的实例并将其传递给另一个外部类的实例。 因此,您需要特定实例才能调用此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; 
    } 
} 
0

我觉得做在内部类外部类的一个实例是不是一个好的选择,因为你可以在外部类的构造函数执行业务逻辑。制作静态方法或属性是更好的选择。如果坚持要创建外部类的实例,则应该将另一个参数添加到不执行业务逻辑的外部类构造器中。

相关问题