我倾向于支持显式接口(interface)实现而不是隐式接口(interface)实现,因为我认为针对接口(interface)而不是针对实现进行编程通常更可取,而且在处理 Web 服务时,这通常是必需的。
也就是说,我想知道为什么以下对于显式接口(interface)声明是非法的,而对于隐式接口(interface)声明是合法的:
interface IConnection
{
string ConnectionString { get; }
}
class Connection1 : IConnection
{
// private set is illegal, won't compile
string IConnection.ConnectionString { get; private set; }
}
class Connection2 : IConnection
{
// private set is legal now, it is not part of the interface
string ConnectionString { get; private set; }
}
我知道如何解决这个问题,因为同时拥有显式和隐式接口(interface)是合法的,而且我可以使隐式接口(interface)实现完全私有(private)。
但我想知道这背后的原因。因为从技术上讲,内部编译的私有(private)方法 set_IConnection_ConnectionString
不需要成为接口(interface)的一部分,对吧?它只能被看作是一个辅助 setter ,而不是接口(interface)的一部分,因为它是在隐式实现情况下。
更新:作为奖励,您收到的看似令人困惑且在我看来不太正确的编译错误如下:
The accessibility modifier of the accessor must be more restrictive than the property Connection1.ConnectionString
请问,比 private
更严格,如何...什么?
最佳答案
调用显式接口(interface)成员的唯一方法是将对象转换为正确的接口(interface),然后在该接口(interface)上调用该成员。但是一旦您转换为 IConnection
,IConnection.ConnectionString
就没有 setter。
因此无法调用这个私有(private) setter 方法。
关于c# - 为什么在显式 getter-only 接口(interface)实现上使用私有(private) setter 是非法的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23611913/