我对C#接口成员的默认访问修饰符感到困惑 [英] I'm confused about default access modifier of C# interface members
问题描述
interface
方法的访问修饰符是什么?它应该是 public
或 protected
,因为您在实现它们时可以访问它们(这是有道理的)。它也应该是 abstract
,因为它们没有实现。但是最近我一直在读一本名为 CLR Via C#的书,关于接口的章节说明如下
What is the access modifier of interface
methods? It should be public
or protected
because you have access to them when you implement them (which makes sense). It also should be abstract
because they don't have implementation. But lately I've been reading a book called CLR Via C# and the chapter about interfaces says the following
CLR要求将
接口
方法标记为virtual
。如果您未在源代码中将该方法明确标记为virtual
,则编译器会将该方法标记为virtual
和已盖好
。
The CLR requires that
interface
methods be marked asvirtual
. If you do not explicitly mark the method asvirtual
in your source code, the compiler marks the method asvirtual
andsealed
.
当您标记界面时
member virtual
编译器抱怨访问修饰符无效。我的意思是没有访问修饰符对 interface
中的任何内容有效,而不是编译器给它们的默认值?有人能说清楚吗?
When you mark the interface
member virtual
compiler complains that the access modifier in not valid. I mean no access modifier is valid for anything in interface
rather than the default one which is given to them by compiler right? Can anyone make it clear for me?
推荐答案
接口可以包含方法,属性,事件,索引器或这四种成员类型的任何
组合。有关示例的链接,请参阅
相关章节。接口不能包含常量,字段,
运算符,实例构造函数,析构函数或类型。 接口
成员自动公开,并且不能包含任何访问
修饰符。成员也不能是静态的。
Interfaces can contain methods, properties, events, indexers, or any combination of those four member types. For links to examples, see Related Sections. An interface can't contain constants, fields, operators, instance constructors, destructors, or types. Interface members are automatically public, and they can't include any access modifiers. Members also can't be static.
关于接口成员的实现:
要实现接口成员,
实现类的相应成员必须是公共的,非静态的,并且具有与接口成员相同的
名称和签名。
To implement an interface member, the corresponding member of the implementing class must be public, non-static, and have the same name and signature as the interface member.
因此,您无法使用 protected
一个实现接口成员。
So you can't implement an interface member using protected
one.
这篇关于我对C#接口成员的默认访问修饰符感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!