C#:私有内部接口可能吗?
我有一个通用类X
; 这个类有一个协变部分,我希望能够协同访问。 所以我把它分解成一个接口IX
。 但是,我希望这个接口只对类本身可见,因为它还包含private
。
即,在课堂内部,我可以向上升到IX
并且共同使用它。 例如:
class X : IX { private interface IX{ // the private covariant interface void foo(); } // It grants access to the private method `foo` private T foo(){...} public T IX.foo(){ return foo(); } private static void someMethod(IX x) { // Here I can use `x` covariantly } }
这可能吗? 我以前从未听说过private
嵌套接口,因为私有接口通常根本就没有。 然而,对于generics,这种接口对于实现“仅私有协方差”是必要的。
当我尝试编译它时,我收到以下错误:
foo.cs(1,14): error CS0246: The type or namespace name `IX' could not be found. Are you missing an assembly reference? foo.cs(9,14): error CS0305: Using the generic type `X.IX' requires `1' type argument(s)
基本上很清楚,generics类型的内部类型需要外部类型的类型参数。 有没有办法让这些代码正确编译?
编辑:看起来这样编译在Roslyn / C#6技术预览版上 ,但不能在MS C#5编译器或单声道编译器上编译。
是的,就像这样 – 但请注意,实际上内部T
在许多方面是不必要的,如果你保留它 – 将它命名为TInner
或其他东西以避免混淆是有用的,因为X
的T
在技术上是不同的事物比X<>.IX
,即使它们在实践中总是相同的实际类型:
class X : X .IX { private interface IX { // the private covariant interface void foo(); } // It grants access to the private method `foo` private T foo() { throw new NotImplementedException(); } void X.IX .foo() { throw new NotImplementedException(); } private static void someMethod(IX x) { // Here I can use `x` covariantly } }
为了编译并限制界面对程序集的可见性,您可以将其标记为内部。 问题是,如果它被声明为内部类型,那么你的class级就不会看到它。 这段代码应该有效:
internal interface IX // the private covariant interface { T foo(); } class X : IX { // It grants access to the private method `foo` private T foo(){ return default(T); } T IX .foo(){ return foo(); } private static void someMethod(IX x) { // Here I can use `x` covariantly } }
这样接口仍然是私有的,但因为它不再是内部类型,所以它可以在你的类上使用。