c#8中的公共接口成员

编程入门 行业动态 更新时间:2024-10-27 23:30:32
本文介绍了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 ?

推荐答案

在 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中的公共接口成员

本文发布于:2023-11-15 21:14:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598013.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   成员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!