隐式内部接口实现

implicit internal interface implementation

当我有一个public接口时

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.

这毫无意义。接口只有internal,为什么还需要public修饰符?为什么必须始终在隐式接口实现中使用 public 是否有任何技术原因,或者 C# 开发人员是否可以采用不同的方式(无需更改语言中的很多东西)?

The modifier must be public because the interface is public.

虽然那是 确定它的方式:那不是编译器想要的。对于隐式接口实现(不管接口类型的可见性),成员必须声明为public,不能声明为"ifs"、"buts"或"maybes"(实现类型,但是,可以是任何可见级别)

绝对是语言设计者可以研究更复杂的规则,但是:由于还有一个选项用于explicit接口实现,他们大概觉得没有必要这样做。


具体来说,这是规范 (v5) 中的 §18.6.5 ("Interface mapping") - 强调我的("I"=接口类型,"M"=成员,"S"=实现类型):

  • If S contains a declaration of an explicit interface member implementation that matches I and M, then this member is the implementation of I.M.
  • Otherwise, if S contains a declaration of a non-static public member that matches M, then this member is the implementation of I.M. If more than one member matches, it is unspecified which member is the implementation of I.M. This situation can only occur if S is a constructed type where the two members as declared in the generic type have different signatures, but the type arguments make their signatures identical.