为什么我需要在C#显式实现中将'this'转换为接口类型? [英] Why do I need to cast 'this' to interface type in a C# explicit implementation?
问题描述
我有一个界面:
public interface Profile
{
string Name { get; }
string Alias { get; set; }
}
所有实现 Profile
的对象都有一个 Name
和一个 Alias
,但是有些对象会限制 Alias
,这样始终与 Name
相同.施加此限制的用户可以这样实现 Alias
:
All objects that implement Profile
have a Name
and an Alias
, but some restrict Alias
such that it's always the same as Name
. The ones that apply this restriction can implement Alias
like this:
string Profile.Alias
{
get
{
return ((Profile)this).Name;
}
set { }
}
因为在明确接口实现的上下文中, this
只能是 Profile
类型,我们知道它是通过 Profile
访问的接口而不是包含类的接口或它实现的任何其他接口,为什么需要强制转换?
Since this
within the context of an explicit interface implementation can only possibly be of type Profile
and we know it was accessed through the Profile
interface rather than that of the containing class or any other interface it implements, why is the cast required?
为getter实现使用 return this.Name;
会导致以下错误:
Using return this.Name;
for the getter implementation results in this error:
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
这不是事实.您正在 ConcreteProfile
类中实现 Profile.Alias
.在这种情况下, this
指的是 ConcreteProfile
实例,可用于访问 ConcreteProfile
实例的任何成员.
This is not true. You are implementing Profile.Alias
inside the ConcreteProfile
class. In this context, this
refers to the ConcreteProfile
instance and can be used to access any member of the ConcreteProfile
instance.
例如, ConcreteProfile
类可以包含另一个 Name
属性,而不是 Profile.Name
.在这种情况下, this.Name
将引用该属性.
For example, the ConcreteProfile
class can contain another Name
property that is not Profile.Name
. In this case this.Name
would refer to that property.
由于要访问 Profile.Name
,因此必须将 this
强制转换为 Profile
.
Since you want to access Profile.Name
, you have to cast this
to Profile
.
这篇关于为什么我需要在C#显式实现中将'this'转换为接口类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!