问题
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