C#: Is a private inner interface possible?

左心房为你撑大大i 提交于 2019-12-04 06:45:24

Edit: 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.


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

In order for it to compile and limit the visibility of your interface just to your assembly you can mark it as internal. The thing is if it's declared as an inner type it won't be seen by your class. This code should work:

internal interface IX<out T> // the private covariant interface
{ 
    T foo();
}

class X<T> : IX<T> 
{
    // It grants access to the private method `foo`
    private T foo(){ return default(T); }
    T IX<T>.foo(){ return foo(); }

    private static void someMethod(IX<T> x)
    {
        // Here I can use `x` covariantly
    }
}

This way the interface is still private, but as it's not an inner type anymore it can be used on your class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!