无法通过嵌套类型访问外部类型的非静态成员
问题描述:
我有错误
无法通过以下方式访问外部类型Project.Neuro"的非静态成员嵌套类型Project.Neuro.Net"
Cannot access a non-static member of outer type 'Project.Neuro' via nested type 'Project.Neuro.Net'
像这样的代码(简化):
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.
我是一个客观的编程新手.
Im kind of objective programming newbie.
提前致谢.
答
问题在于嵌套类不是派生类,所以外层类中的方法是不是继承.
The problem is that nested classes are not derived classes, so the methods in the outer class are not inherited.
有些选项是
使方法
static
:
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();
}
}
创建一个Neuro
的实例:
class Neuro
{
public class Net
{
public void SomeMethod()
{
Neuro n = new Neuro();
int x = n.OtherMethod();
}
}
public int OtherMethod()
{
return 123;
}
}