public interface member in c#8

限于喜欢 提交于 2020-01-15 03:10:51

问题


Since the latest version of c#, it is possible to write the following interface:

public interface IMyInterface
{
    public void MyMethod();
}

This seems like a code smell to me, as I feel like the intention was to write the previously available:

public interface IMyInterface
{
    void MyMethod();
}

Are those two interfaces exactly the same ? Does the public keyword add/changes anything ? Is this something that should be corrected, or am I wrong and should public be consistently used now ?


回答1:


Being able to set an explicit access modifier was added with the introduction of default interface methods that came with C# 8. Default interface methods support different access modifiers, so it makes sense at least for consistency to be able to specify access modifiers for all members. If you specify an access modifier that's invalid (e.g. a private method with no body), the code will not compile.

Are those two interfaces exactly the same ? Does the public keyword add/changes anything ?

Yes, the default access modifier is public. Setting it explicitly gives the same result.

Is this something that should be corrected, or am I wrong and should public be consistently used now ?

It's up to you. If you like to use private for fields in classes, for example, then you might like to apply that same explicitness in your interfaces for public, now that it's possible.

The default interface methods specification proposal goes into the specifics of the access modifier change.



来源:https://stackoverflow.com/questions/58972582/public-interface-member-in-c8

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