用基类预混合属性
本文关键字:属性 混合 基类 | 更新日期: 2023-09-27 18:00:38
我有一个接口,它的属性如下:
public interface IMyInterface
{
IGenericThing MyProperty { get; set; }
}
我在一个使用泛型类型的特定类中实现了该接口,但在该类中,我想使用IGenericThing的特定实现,如下所示:
public abstract class MySpecificClass<T> : IMyInterface
where T : IGenericThing
{
IGenericThing IMyInterface.MyProperty
{
get { return myProperty; }
set
{
if (value is T)
{
MyProperty = (T)value;
}
}
}
protected T myProperty;
public T MyProperty
{
get { return myProperty; }
set
{
myProperty = value;
//...other setter stuff
}
}
}
这一切都奏效了,太棒了。当我通过IMyInterface引用对象时,它允许我访问MyProperty,当我知道它是MySpecificClass的实例时,它可以访问有关MyProperty的更具体的信息。
我真正不明白的是这被称为什么,或者编译器是如何让这种情况发生的。我试着搜索这个,但由于我不知道它叫什么,所以什么都找不到。
有人能解释一下这里发生了什么吗?这样我就能更好地理解这一点?
这被称为显式接口实现
如果一个类实现了两个接口,其中包含一个具有相同签名的成员,那么在该类上实现该成员将导致两个接口都使用该成员作为其实现。
这并不完全是你的情况,但在这里你有一个经典的用法
interface IControl
{
void Paint();
}
interface ISurface
{
void Paint();
}
public class SampleClass : IControl, ISurface
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}
}