由于c#是最新版本,因此可以编写以下接口:
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(); }这两个接口完全相同吗? public关键字是否添加/更改了任何内容?这是应该纠正的事情,还是我错了,应该现在始终使用public?
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 ?
推荐答案在 C#8随附的默认接口方法.默认接口方法支持不同的访问修饰符,因此至少出于一致性考虑以便为所有成员指定访问修饰符.如果您指定了无效的访问修饰符(例如,没有正文的private方法),则代码将无法编译.
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.
这两个接口完全相同吗? public关键字是否添加/更改了任何内容?
Are those two interfaces exactly the same ? Does the public keyword add/changes anything ?
是的,默认访问修饰符为public.明确设置 可获得相同的结果.
Yes, the default access modifier is public. Setting it explicitly gives the same result.
这是应该纠正的问题,还是我错了,应该现在始终使用public吗?
由您决定.例如,如果您想对类中的字段使用private,那么您现在可能想在public的接口中应用相同的显式性.
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.
更多推荐
c#8中的公共接口成员
发布评论