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之前的接口成员而言,这并不是严格的唯一方法。为什么新成员有什么不同?
看来这是设计使然。这是相关的文本:
隐式实现非公共接口成员
我们是否允许隐式实现非公共接口成员?如果是这样,对实现方法的可访问性有何要求?一些选项:
- 必须公开
- 必须具有完全相同的可访问性
- 必须至少具有可访问性
结论
现在,让我们简单地不允许它。只能隐式实现公共接口成员(并且只能由公共成员实现)。我们可以通过思考来放松自己。
显然,带有访问修饰符的接口方法将不能与以前版本的接口成员完全按照相同的规则播放,因为它们只能是公共的。
至于为什么要这样,这是设计师的一个问题。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)
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |