C# 中的 Java 内部类
我有以下 Java 代码:
public class A {
private int var_a = 666;
public A() {
B b = new B();
b.method123();
System.out.println(b.var_b);
}
public class B {
private int var_b = 999;
public void method123() {
System.out.println(A.this.var_a);
}
}
}
产生 666 和 999。 现在,我尝试在 C# 中设置类似的代码,但似乎不可能完成相同的任务。如果是这样的话,您在使用 C# 编程时通常如何实现类似的效果?
I have the following Java code:
public class A {
private int var_a = 666;
public A() {
B b = new B();
b.method123();
System.out.println(b.var_b);
}
public class B {
private int var_b = 999;
public void method123() {
System.out.println(A.this.var_a);
}
}
}
Which yields 666 and 999. Now, I've tried to set up similar code in c#, but it seems that it is not possible to accomplish the same. If that's the case, how you usually achieve a similar effect when programming in c#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要使内部类将外部类的实例作为构造函数参数。 (Java编译器是这样实现内部类的)
You need to make the inner class take an instance of the outer class as a constructor parameter. (This is how the Java compiler implements inner classes)
C# 和 Java 之间的内部类处理方式略有不同。 Java 隐式将对外部类实例的引用传递给内部类,允许内部类访问外部类的字段。要在 C# 中获得类似的功能,您只需显式执行 Java 隐式执行的操作即可。
请参阅本文了解更多信息。
Inner classes are handled slightly differently between C# and Java. Java implicitly passes a reference to an instance of the outer class to the inner class, allowing the inner class to access fields of the outer class. To gain similar functionality in C#, you just have to do explicitly what Java does implicitly.
Check out this article for some more information.
从 Java 角度来看,C# 内部类就像 Java 嵌套类(如果在代码中声明
public static class B
就会得到这样的结果)。差异的原因是 C# 支持委托,它取代了 Java 内部类的主要用例。一旦使用语言中的委托,C# 的设计者就觉得没有必要在内部类和嵌套类之间添加区别。
From a Java perspective, C# inner classes are like java nested classes (what you get if you declare
public static class B
in your code).The reason for the difference is that C# supports delegates, which replaces the major use case for Java inner classes. Once delegates are in the language the designers of C# felt it unnecessary to add a distinction between inner and nested classes.
这是您的代码:
var_b 需要是内部的,位于私有和公共之间,意味着“可访问命名空间类”:
here is your code:
var_b need to be internal, which is between private and public and means like "accessible for namespace-classes":