且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我需要在C#显式实现中将'this'转换为接口类型?

更新时间:2022-11-23 12:01:51

因为在明确接口实现的上下文中, 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.