简体   繁体   English

在内部/本地/匿名类方面,Java和C#之间的根本区别是什么?

[英]What are the fundamental differences between Java and C# in terms of inner/local/anonymous classes?

内部/本地/匿名类方面,Java和C#之间的根本区别是什么?

C# doesn't have the equivalent of Java inner classes - it only has nested types (like Java's "static" nested classes). C#没有Java内部类的等价物 - 它只有嵌套类型(如Java的“静态”嵌套类)。

The access rules are slightly different - in Java, an outer class has access to its nested class's private members, and vice versa. 访问规则略有不同 - 在Java中,外部类可以访问其嵌套类的私有成员,反之亦然。 In C# the nested class has access to the outer class's private members, but not the other way round. 在C#中,嵌套类可以访问外部类的私有成员,但不能反过来。

C# doesn't have anonymous inner classes like Java, but it does have anonymous methods and lambda expressions, which are a much cleaner way of achieving most of what anonymous inner classes are usually used for. C#没有像Java那样的匿名内部类,但它确实有匿名方法和lambda表达式,这是实现大多数匿名内部类通常用于的大多数方法。 The variable capture for the two mechanisms is different - see my article on closures for more details. 两种机制的变量捕获是不同的 - 有关更多详细信息,请参阅我关于闭包的文章

In my mind, the biggest difference is how they (anonymous classes in java vs anonymous methods in C#) handle captures. 在我看来,最大的区别在于它们(Java中的匿名类与C#中的匿名方法)如何处理捕获。 In java, it captures the current value of the variable (the original and captured value are then isolated). 在java中,它捕获变量的当前 (然后隔离原始和捕获的值)。 In C#, you capture the variable itself. 在C#中,您可以捕获变量本身。 This is double edged, and can lead to problems - but is incredibly powerful when used correctly. 这是双刃剑,可能会导致问题 - 但如果使用得当,它会非常强大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM