加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#:私有内部接口可能吗?

发布时间:2020-12-15 08:14:16 所属栏目:百科 来源:网络整理
导读:我有一个通用类X Tgt ;;这个类有一个协变部分,我希望能够协同访问.因此,我将其分解为接口IX out T.但是,我希望这个接口只对类本身可见,因为它还包含私有的方法. 即,在课堂内部,我可以向上转换为IX T.并且协同使用它.例如.: class XT : IXT { private interf
我有一个通用类X< T&gt ;;这个类有一个协变部分,我希望能够协同访问.因此,我将其分解为接口IX< out T>.但是,我希望这个接口只对类本身可见,因为它还包含私有的方法.

即,在课堂内部,我可以向上转换为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
    }
}

这可能吗?我之前从未听说过私有嵌套接口,因为私有接口通常根本就没有.然而,对于泛型,这种接口对于实现“仅私有协方差”是必要的.

当我尝试编译它时,我收到以下错误:

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或其他东西以避免混淆是有用的,因为X< T>中的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
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读