显式接口实现(Explicit interface implementation)不允许您指定任何访问修饰符。当您通过在成员名称之前指定接口名称来显式实现接口成员时,您只能使用该接口访问该成员。基本上,如果您这样做:
System.Collections.Specialized.StringDictionary IWorkItemControl.Properties
{
get { return properties; }
set { properties = value; }
}
您不能这样做:
MyClass x = new MyClass()
var test = x.Properties
// You should do:
var test = ((IWorkItemControl)x).Properties
企业级集成(EII)有几个用例。例如,您想为类提供Close
方法以释放已获取的资源,但仍想实现IDisposable
。可以这样做:
class Test : IDisposable {
public void Close() {
}
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,甚至不可能在单个类中实现此示例的两个接口(因为属性仅在返回类型上有所不同)。 在其他情况下,您可能希望通过不同的接口为类的各个视图提供不同的行为。