我有一个通用类 X<T>
;这个类有一个协变部分,我希望能够协变地访问它。所以我把它分解成一个界面 IX<out T>
.但是,我希望这个接口(interface)只对类本身可见,因为它还包含被称为 private
的方法。 .
即,在类本身内部,我可以向上转换为 IX<T>
并协变地使用它。例如:
class X<T> : IX<T> {
private interface IX<out T>{ // 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<T> x) {
// Here I can use `x` covariantly
}
}
这可能吗?我从没听说过 private
之前嵌套接口(interface),因为私有(private)接口(interface)通常根本没有意义。但是,对于泛型,这样的接口(interface)对于实现“仅私有(private)协变”是必要的。
当我尝试编译它时,我收到以下错误:
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<T>.IX<S>' requires `1' type argument(s)
基本上很清楚,泛型类型的内部类型需要外部类型的类型参数。有没有办法让这段代码正确编译?
最佳答案
编辑:它看起来像是在 Roslyn / C# 6 tech preview 上编译的, 但不在 MS C# 5 编译器或单声道编译器上编译。
是的,就像这样 - 但请注意实际上内部 T
在很多方面都是不必要的,如果你保留它 - 将它命名为 TInner
会很有用。或一些避免混淆的东西,因为 T
在 X<T>
技术上与X<>.IX<T>
是不同的东西,即使它们在实践中始终是相同的实际类型:
class X<T> : X<T>.IX<T>
{
private interface IX<out TInner>
{ // the private covariant interface
void foo();
}
// It grants access to the private method `foo`
private T foo() { throw new NotImplementedException(); }
void X<T>.IX<T>.foo() { throw new NotImplementedException(); }
private static void someMethod(IX<T> x)
{
// Here I can use `x` covariantly
}
}
关于C#:私有(private)内部接口(interface)是否可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24820885/