C# 中接口成员的访问修饰符
我从以下属性中收到编译错误。
错误是:
“修饰符‘public’对此项目无效”
public System.Collections.Specialized.StringDictionary IWorkItemControl.Properties
{
get { return properties; }
set { properties = value; }
}
但如果我删除 IWorkItemControl
它编译正常。
为什么我会收到此错误?签名中包含/不包含接口名称有什么区别?
I am getting a compile error from the following property.
The error is:
"The modifier 'public' is not valid for this item"
public System.Collections.Specialized.StringDictionary IWorkItemControl.Properties
{
get { return properties; }
set { properties = value; }
}
but if I remove the IWorkItemControl
it compiles fine.
Why am I getting this error and what is the difference of having / not having the interface name in the signature?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
显式接口实现不允许您指定任何访问修饰符。 当您显式实现接口成员时(通过在成员名称之前指定接口名称),您可以仅使用该接口访问该成员。 基本上,如果您这样做:
您不能这样做:
EII 有多种用例。 例如,您希望为您的类提供一个
Close
方法来释放获取的资源,但您仍然希望实现IDisposable
。 你可以这样做:这样,类的使用者只能直接调用
Close
(他们甚至不会在 Intellisense 列表中看到Dispose
),但你仍然可以使用 < code>Test 类中任何需要IDisposable
的地方(例如在using
语句中)。EII 的另一个用例是为两个接口提供同名接口成员的不同实现:
如您所见,如果没有 EII,甚至不可能在单个类中实现此示例的两个接口(如属性仅在返回类型上有所不同)。 在其他情况下,您可能希望通过不同的接口有意为类的各个视图提供不同的行为。
Explicit interface implementation does not let you specify any access modifiers. When you implement an interface member explicitly (by specifying the interface name before the member name), you can access that member only using that interface. Basically, if you do:
You can't do:
There are several use cases for EII. For example, you want to provide a
Close
method for your class to free up acquired resources but you still want to implementIDisposable
. You could do:This way, the consumers of class can only call
Close
directly (and they won't even seeDispose
in Intellisense list) but you can still use theTest
class wherever anIDisposable
is expected (e.g. in ausing
statement).Another use case for EII is providing different implementations of an identically named interface member for two interfaces:
As you see, without EII it's not even possible to implement both interfaces of this example in a single class (as the properties differ just in return type). In other cases, you might want to intentionally provide different behavior for individual views of a class through different interfaces.
接口的所有元素都必须是公共的。
毕竟,接口是对象的公共视图。
由于 Properties 是接口 IWorkItemControl 的一个元素,因此它已经是公共的,您无法指定其访问级别,甚至无法冗余地指定它是公共的。
All elements of an interface must be public.
After all, an interface is the public view of an object.
Since Properties is an element of an interface IWorkItemControl, it is already public, and you cannot specify its access level, even to redundantly specify that it is public.