嵌套类型问题
我只是尝试创建这个简单的实现:
class Test
{
private int abc = 0;
public class TestClass
{
private void changeABC()
{
abc = 123;
}
}
}
如果我编译它,它会抱怨:
无法通过嵌套类型“B.Test.TestClass”访问外部类型“A.Test”的非静态成员
我不喜欢设置的解决方案: static int abc = 0;
还有其他吗解决这个问题?
I just tried to create this simple implementation:
class Test
{
private int abc = 0;
public class TestClass
{
private void changeABC()
{
abc = 123;
}
}
}
If I compile it, it will complain:
Cannot access a non-static member of outer type 'A.Test' via nested type 'B.Test.TestClass'
I dont like the solution of setting: static int abc = 0;
Is there any other solution for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能有 Java 背景,这段代码可以按预期工作。
在 C# 中,嵌套类型是静态的(用 Java 的说法),即它们不绑定到父类的实例。这就是您的代码失败的原因。您需要以某种方式将父类的实例传递给子类并访问其成员
abc
。You are probably coming from a Java background where this code would work as expected.
In C#, nested types are static (in the parlance of Java), i.e. they are not bound to an instance of the parent class. This is why your code fails. You need to somehow pass an instance of the parent class to the child class and access its member
abc
.内部类需要引用外部类的实例:
The inner class needs a reference to an instance of the outer class:
我不明白为什么
TestClass
应该 在其实例类时更改父Test
。也许我的例子可以阐明这一点:
像这样使用:
I don't see why
TestClass
should change the parentTest
when its an instance class.Maybe me example would shed light on this:
Use Like this:
来自 C# 嵌套类就像 C++ 嵌套类,而不是 Java 内部类
From C# nested classes are like C++ nested classes, not Java inner classes