Why must methods implementing internal interfaces be public

后端 未结 2 820
情话喂你
情话喂你 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.

    0 讨论(0)
  • 2021-01-13 13:28

    Simply put: because that's the way the language designers designed it. Even in internal interfaces, the methods are implicitly public. It does make things simple, but it's a pain in other ways.

    If you want a public class where you want to "hide" the use of an internal interface, you could use explicit interface implementation - although that has other drawbacks.

    Of course, if your class is internal then it doesn't matter that the methods are public anyway - other assemblies aren't going to be able to call the methods because they can't see the type.

    I definitely agree that C# (or .NET in general) hasn't been designed as carefully as it might be around internal interfaces.

    In terms of exactly why you're getting an error message - section 13.4.4 of the C# 4 spec (interface mapping) is the reason. Implementations are only found for nonstatic public members and explicit interface member implementations - and if there are any unimplemented members in the interface, an error occurs.

    0 讨论(0)
提交回复
热议问题