C#:是一个私有内部接口,可能吗? [英] C#: Is a private inner interface possible?

查看:181
本文介绍了C#:是一个私有内部接口,可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个泛型类 X< T> ;这个类有,我希望能够访问一个协变协变的一部分。所以,我是因素伸到接口 IX<出T> 。不过,我想这个接口是可见只对类本身,因为它也包含对彪是私人

I have a generic class X<T>; This class has a covariant part that I want to be able to access covariantly. So I factor it out into an interface IX<out T>. However, I want this interface to be visible only to the class itself, because it contains also methods that are ment to be private.

即类本身里面,我可以上溯造型到 IX< T> 和协变使用它。 。例如:

I.e., inside the class itself, I can upcast to IX<T> and use it covariantly. E.g.:

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
    }
}

这可能吗?我从来没有听说过的私人嵌套接口之前,因为私有接口通常是没有SENCE可言。然而,随着仿制药这样的接口有必要实施私人专用协

Is this possible? I have never heard of private nested interfaces before, since a private interface usually makes no sence at all. However, with generics such an interface becomes necessary for implementing "private-only covariance".

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

When I try to compile this, I receive the following error:

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)

这基本上是清楚的,内部类型泛型类型的需求外类型的类型参数。 ?有没有办法得到这个代码正确编译

Which is basically clear, an inner type of a generic type needs a type parameter for the outer type. Is there a way to get this code to compile correctly?

推荐答案

编辑:它看起来像这样编译上的Roslyn / C#6技术预览,但在MS C#编译器5或单声道编译器不会编译。但要注意,其实里面的 T

it looks like this compiles on the Roslyn / C# 6 tech preview, but does not compile on the MS C# 5 compiler or the mono compiler.

是的,像这样的>在许多方面是不必要的,如果你保留它 - 这将是它命名为 TINNER 或东西,以避免混淆有用,因为 T X< T> 是技术上的不同的东西比 X<> .IX< T> ,即使他们将永远是同样的类型在实践中:

Yes, like this - but note that actually the inner T is unnecessary in many ways, and if you retain it - it would be useful to name it TInner or something to avoid confusion, since the T in X<T> is technically a different thing than X<>.IX<T>, even though they will always be the same actual type in practice:

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#:是一个私有内部接口,可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆