【发布时间】:2016-03-16 22:48:45
【问题描述】:
我有一个界面:
public interface Profile
{
string Name { get; }
string Alias { get; set; }
}
所有实现Profile 的对象都有Name 和Alias,但有些限制Alias 使其始终与Name 相同。应用此限制的可以像这样实现Alias:
string Profile.Alias
{
get
{
return ((Profile)this).Name;
}
set { }
}
由于在显式接口实现的上下文中this 只能是Profile 类型,并且我们知道它是通过Profile 接口而不是包含类或它实现的任何其他接口的接口访问的,为什么需要演员表?
将return this.Name; 用于getter 实现会导致此错误:
Type `ConcreteProfile' does not contain a definition for `Name' and no extension method `Name' of type `ConcreteProfile' could be found (are you missing a using directive or an assembly reference?)
【问题讨论】:
-
为什么不简单地使用 string Alias => Name (c#6) 或 string Alias {get { return Name;}} ?
-
@Boo:因为它需要实现接口,它有一个setter。就我个人而言,我会让 setter 抛出异常,而不是忽略调用……或者重新设计界面。
标签: c# interface explicit-interface