Why must methods implementing internal interfaces be public

后端 未结 2 819
情话喂你
情话喂你 2021-01-13 13:06

I am developing an internal class that implements an internal interface. Can anyone explain why I cannot declare my method as internal, why I am getting the following error

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 13:21

    I know this is old but maybe someone find it useful. You can accomplish a kind of internal interface methods like this:

    internal interface IFoo
    {
        void MyMethod();
    }
    
    public abstract class Foo : IFoo
    {
        void IFoo.MyMethod()
        {
            MyMethod();
        }
    
        internal abstract void MyMethod();
    }
    

    So all your internal classes should derive from Foo and are forced to implement the abstract MyMethod. But you can treat them all as IFoo of course. But those classes outside the assembly won't provide the MyMethod class.

    So you have the advantage to treat your classes internally as IFoo and rely on MyMethod. The drawback is that all your classes will need to derive from Foo which can be a problem if you need another base class.

    But I found it helpful if the abstract base class is a generic one and the interface is not. Maybe it is useful in some cases.

提交回复
热议问题