c#8中的公共接口成员 [英] public interface member in c#8
问题描述
由于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 ?
推荐答案
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中的公共接口成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!