C#中接口成员的访问修饰符

我从以下属性收到编译错误。
错误是:

“修饰符’public’对此项无效”

public System.Collections.Specialized.StringDictionary IWorkItemControl.Properties { get { return properties; } set { properties = value; } } 

但如果我删除IWorkItemControl它编译得很好。

为什么我会收到此错误,签名中是否有/没有接口名称有什么区别?

显式接口实现不允许您指定任何访问修饰符。 当您显式实现接口成员时(通过在成员名称之前指定接口名称),您只能使用该接口访问该成员。 基本上,如果你这样做:

 System.Collections.Specialized.StringDictionary IWorkItemControl.Properties { get { return properties; } set { properties = value; } } 

你做不到:

 MyClass x = new MyClass(); var test = x.Properties; // fails to compile // You should do: var test = ((IWorkItemControl)x).Properties; // accessible through the interface 

EII有几个用例。 例如,您希望为类提供Close方法以释放已获取的资源,但您仍希望实现IDisposable 。 你可以这样做:

 class Test : IDisposable { public void Close() { // Frees up resources } void IDisposable.Dispose() { Close(); } } 

这样,类的使用者只能直接调用Close (他们甚至不会在Intellisense列表中看到Dispose ),但是你仍然可以在任何需要IDisposable地方使用Test类(例如在using语句中)。

EII的另一个用例是为两个接口提供同名的接口成员的不同实现:

 interface IOne { bool Property { get; } } interface ITwo { string Property { get; } } class Test : IOne, ITwo { bool IOne.Property { ... } string ITwo.Property { ... } } 

如您所见,没有EII, 甚至不可能在单个类中实现此示例的两个接口(因为属性在返回类型上不同)。 在其他情况下,您可能希望通过不同的接口有意为类的各个视图提供不同的行为。

界面的所有元素都必须是公共的。 毕竟,接口对象的公共视图。

由于PropertiesIWorkItemControl接口的一个元素,因此它已经公开,您无法指定其访问级别,甚至可以冗余地指定它是公共的。