【问题标题】:Prefixing a property with base class使用基类为属性添加前缀
【发布时间】:2015-07-01 19:02:26
【问题描述】:

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

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 的更多具体信息。

我真正不明白的是这被称为什么或者编译器正在做什么来让这种情况发生。我试图搜索这个,但由于我不知道它叫什么,所以找不到任何东西。

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

【问题讨论】:

  • 称为显式接口实现

标签: c# oop inheritance polymorphism


【解决方案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");
    }
}

【讨论】:

  • 谢谢!我使用接口的次数越多,我就越喜欢你可以用它们做的一些事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-18
  • 2013-06-22
  • 2018-05-29
相关资源
最近更新 更多