为什么C#不支持接口实现成员的隐式接口转换?

时间:2019-01-09 16:26:54

标签: c# interface

考虑一下:

   interface IA
    {

    }

    public class A : IA
    {

    }

    interface IB
    {
         IA PropertyA { get; set; }
    }


    class B : IB
    {
        public A PropertyA { get; set; }
    }

这是不允许的,因为类B没有实现IA类型的propertyA。此类中的IE PropertyA在类中不是IA,而是类型A。

但这似乎很遗憾,因为A支持IA,对于编译器/语言来说,支持它并隐式处理转换应该是微不足道的。

如果允许这种设计模式,它会非常有用,因为它可以自动生成抽象其实现的类的接口模型。有人知道任何解决方法吗?

1 个答案:

答案 0 :(得分:3)

它不起作用,因为它可以编译,但是会在运行时爆炸:

public class A2 : IA
{
}

B b = new B();  // fine
IB ib = b;      // fine
ib.PropertyA = new A2();  // blows up at runtime since B can only hold A objects in PropertyA
  

有人知道任何解决方法吗?

泛型:

interface IB<T> where T:IA
{
     T PropertyA { get; set; }
}

class B : IB<A>
{
    public A PropertyA { get; set; }
}