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

ben*_*rce 16 c# interface access-modifiers explicit-interface

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

"修饰符'public'对此项无效"

public System.Collections.Specialized.StringDictionary IWorkItemControl.Properties
{
    get { return properties; }
    set { properties = value; }
}
Run Code Online (Sandbox Code Playgroud)

但如果我删除IWorkItemControl它编译好.

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

Meh*_*ari 41

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

System.Collections.Specialized.StringDictionary IWorkItemControl.Properties
{
    get { return properties; }
    set { properties = value; }
}
Run Code Online (Sandbox Code Playgroud)

你做不到:

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

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

class Test : IDisposable {
    public void Close() {
        // Frees up resources
    }
    void IDisposable.Dispose() {
        Close();
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,类的使用者只能Close直接调用(并且他们甚至不会Dispose在Intellisense列表中看到),但您仍然可以在Test任何IDisposable预期的地方使用该类(例如在using语句中).

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

interface IOne {
   bool Property { get; }
}

interface ITwo {
   string Property { get; }
}

class Test : IOne, ITwo {
   bool IOne.Property { ... }
   string ITwo.Property { ... }
}
Run Code Online (Sandbox Code Playgroud)

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