使用基类前缀属性

时间:2015-07-01 19:02:26

标签: c# oop inheritance polymorphism

我有一个具有如下属性的接口:

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的更多特定信息。

我真正理解的是这个被调用的内容或者编译器正在做些什么来实现这一点。我试着搜索这个,但由于我不知道它叫什么,所以找不到任何东西。

有人可以解释一下这里发生了什么,以便我能更好地理解这一点吗?

1 个答案:

答案 0 :(得分:1)

这叫做explicit interface implementation

  

如果一个类实现了两个包含具有相同签名的成员的接口,那么在该类上实现该成员将导致两个接口都使用该成员作为其实现。

这不完全是你的情况,但在这里你有一个经典的用法

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");
    }
}