隐式内部接口实现

时间:2018-12-07 10:28:17

标签: c# interface implicit-conversion

当我有公共界面时

public interface IPub { string Foo { get; set; } }

然后我可以通过显式地实现此接口:

public class CFoo : IPub { string IPub.Foo { get; set; } }

或使用public修饰符隐式:

public class CFoo : IPub { public string Foo { get; set; } }

。很有道理:修饰符必须为public,因为接口为public

但是当我有内部接口时

internal interface IInt { string Bar { get; set; } }

然后我只能明确实现它:

public class CBar : IInt { string IInt.Bar { get; set; } }

或隐式使用public修饰符:

public class CBar : IInt { public string Bar { get; set; } }

,但不能使用internal修饰符:

public class CBar : IInt { internal string Bar { get; set; } }
// compiler error:
//     'CBar' does not implement interface member 'IInt.Bar'.
//     'CBar.Bar' cannot implement an interface member
//      because it is not public.

这没有意义。当界面只有public时为什么需要一个internal修饰符?有任何技术上的原因为什么必须始终在隐式接口实现中使用public,还是C#开发人员可以采用不同的方式(无需更改语言中的许多内容)?

1 个答案:

答案 0 :(得分:6)

  

修饰符必须是公共的,因为接口是公共的。

虽然这可能是一种确定方式:这不是编译器想要的。对于隐式接口实现(无论接口类型的可见性如何),必须将成员声明为public,不得声明“ ifs”,“ buts”或“ maybes”(实现类型 ,但是可以是任何可见度级别)

当然,语言设计师可以研究更复杂的规则,但是:由于还存在 explicit 接口实现的选项,因此他们大概不会这样做是必要的。


具体来说,这是规范(v5)中的§18.6.5(“接口映射”)-强调点(“ I” =接口类型,“ M” =成员,“ S” =实现类型):

  
      
  • 如果S包含与I和M匹配的显式接口成员实现的声明,则   这个成员是I.M的实现。
  •   
  • 否则,如果S包含与M匹配的非静态公共成员的声明,则该成员   是I.M的实现。如果有多个成员匹配,则不确定哪个成员是   I.M.的实现只有在S是两个   泛型类型中声明的成员具有不同的签名,但是类型参数使它们的   签名相同。
  •