我有一个界面:
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;
了此错误,吸气实施效果:
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?)
因为
this
在显式接口的上下文中,实现只能是类型Profile
这不是真的。您正在类Profile.Alias
内部实现ConcreteProfile
。在这种情况下,this
指的是ConcreteProfile
实例,可用于访问ConcreteProfile
实例的任何成员。
例如,ConcreteProfile
该类可以包含另一个Name
属性not Profile.Name
。在这种情况下,this.Name
将引用该属性。
由于要访问Profile.Name
,因此必须强制转换this
为Profile
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句