首页 > 解决方案 > C# 允许接口属性重载的原因是什么?

问题描述

这个问题很可能会揭示我对如何创建良好界面的误解......

假设我有一个ItemClass类,它正在实现IItemInterface接口,如下所示:

public class ItemClass : IItemInterface /* ..... */ 

我也有以下界面:

public interface ClassInterface
{
    List<IItemInterface> Items;
}

现在,假设在此接口的特定实现中,我希望我的 Items 属性比IItemInterface的简单列表更具体。C# 允许我覆盖ClassInterface Items 属性并执行此操作(代码编译/运行完美)

public class MyClass : ClassInterface
{
    public List<ItemClass> Items { get; set;  }

    IList<IItemInterface> MyInterface.Items
    {
        get { return this.Items; }
    }
}

// Method somewhere else
public void foo()
{
    MyClass bar = new MyClass();
    bar.Items = new List<ItemClass>();
    // etc....
}

我的问题是:为什么 C# 允许我这样做?我知道您不允许重载属性,那么为什么对接口进行不同的处理?

标签: c#

解决方案


推荐阅读