我需要在可访问性是内部的嵌套类中重写Equals运算符(并因此重写GetHashcode方法).
当我尝试执行此操作时,编译器会抱怨我无法使用私有方法重写Equals(公共成员).但是我不能将重写公开,因为类本身是内部的并且是嵌套的.
如何做到这一点?如何在非公共类(实际上是嵌套的和内部的)中重写Equals和GetHashcode?
解决方法:
I’m not sure why it works, though.
此行为在C#规范的第3.5.2节中定义:
The accessibility domain of a nested member
M
declared in a typeT
within a programP
is defined as follows (noting that M itself may possibly be a type): […]
- If the declared accessibility of
M
isinternal
, the accessibility domain ofM
is the intersection of the accessibility domain ofT
with the program text ofP
.
这项规定要求,对于具有内部可访问性的类,类型成员可以等效地标记为公共或内部.
You can’t have a member whose access level is higher than it’s containing class?
这是准确的;规范的同一部分指出“成员的可访问性域永远比声明该成员的类型的可访问性域更具包容性”.重要的是要认识到,尽管该语言允许将具有内部可访问性的类型的成员声明为公共,但它仍将具有内部可访问性(就像将其声明为内部一样).
换句话说,在下面的段中,X的可访问性在两行中是等效的:
internal class A {public void X() {}}
internal class A {internal void X() {}}