gpt4 book ai didi

c# - c#8 中的公共(public)接口(interface)成员

转载 作者:太空宇宙 更新时间:2023-11-03 11:57:27 25 4
gpt4 key购买 nike

从最新版的c#开始,可以写出如下接口(interface):

public interface IMyInterface
{
public void MyMethod();
}

这对我来说似乎是一种代码味道,因为我觉得它的目的是编写以前可用的代码:

public interface IMyInterface
{
void MyMethod();
}

这两个界面是否完全相同? public 关键字是否添加/更改任何内容?这是应该纠正的东西,还是我错了,现在应该始终使用 public 吗?

最佳答案

能够设置显式访问修饰符是随着 default interface methods 的引入而添加的C# 8 附带的默认接口(interface)方法支持不同的访问修饰符,因此至少为了一致性能够为所有成员指定访问修饰符是有意义的。如果您指定了一个无效的访问修饰符(例如没有主体的 private 方法),代码将无法编译。

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

是的,默认 访问修饰符是public显式设置它会得到相同的结果。

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

这取决于你。例如,如果您喜欢将 private 用于类中的字段,那么您可能希望在您的接口(interface)中为 public 应用相同的显式性,因为这是可能的。

default interface methods规范提案涉及访问修饰符更改的细节。

关于c# - c#8 中的公共(public)接口(interface)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58972582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com