为 属性 加上基数 class 前缀

Prefixing a property with base class

我的界面有一个 属性 像这样:

public interface IMyInterface
{
    IGenericThing MyProperty { get; set; }
}

我在使用通用类型的特定 class 中实现了该接口,但在那个 class 中,我想使用 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 的更多特定信息。

我不太明白这叫做什么,或者编译器正在做什么来让这种情况发生。我试着搜索这个,但因为我不知道它叫什么,所以找不到任何东西。

任何人都可以解释一下这里发生了什么,以便我更好地理解吗?

那叫explicit interface implementation

if a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their 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");
    }
}