在接口C#8中使用静态,内部和受保护的访问修饰符

Mau*_*eys 3 c# c#-8.0

C#8现在支持接口成员上的访问修饰符,它的用法使我感到困惑。请看下面的例子

public interface IFoobar 
{   // these members are all valid
    protected string Protected { get; set; }
    internal string Internal { get; set; }
    static string Static { get; set; }
}

public class Foobar : IFoobar // <-- error, Internal and Protected members not implemented
{
    protected string Protected { get; set; }
    internal string Internal { get; set; }
    static string Static { get; set; } // only this one implements IFoobar
}
Run Code Online (Sandbox Code Playgroud)

我的期望是Foobar上述将完全实现IFoobar。但是,仅这种情况适用Static,而其他情况并非如此。

有人可以吗

  • 解释为什么它们的行为不同(并且与c#8之前的接口成员也不同)
  • 给我这样的接口中的三个修饰符的用例?

谢谢

[编辑]

我知道使用显式接口实现将实现成员,但是对于c#8之前的接口成员而言,这并不是严格的唯一方法。为什么新成员有什么不同?

Jon*_*ase 5

我知道使用显式接口实现将实现成员,但是对于c#8之前的接口成员而言,这并不是严格的唯一方法。为什么新成员有什么不同?

看来这是设计使然。这是相关的文本:

隐式实现非公共接口成员

我们是否允许隐式实现非公共接口成员?如果是这样,对实现方法的可访问性有何要求?一些选项:

  • 必须公开
  • 必须具有完全相同的可访问性
  • 必须至少具有可访问性

结论

现在,让我们简单地不允许它。只能隐式实现公共接口成员(并且只能由公共成员实现)。我们可以通过思考来放松自己。

显然,带有访问修饰符的接口方法将不能与以前版本的接口成员完全按照相同的规则播放,因为它们只能是公共的。

至于为什么要这样,这是设计师的一个问题。LDM的措辞也听起来并不像是一成不变的。所以,也许隐含实现接入改性成员将在未来允许的。

现在,实现此接口的方法将是显式地实现,例如:

public interface IFoobar
{   // these members are all valid
    protected string Protected { get; set; }
    internal string Internal { get; set; }
    static string Static { get; set; }
}

public class Foobar : IFoobar
{
    string IFoobar.Protected {get;set;}
    string IFoobar.Internal {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

  • 他们似乎非常了解“任何隐含事物可能有多危险”。您以后总是可以隐式添加。但是,您永远无法删除它。 (2认同)