Multiple Generics ambiguity

后端 未结 2 1707
名媛妹妹
名媛妹妹 2021-01-06 06:33

The codes below are exactly the same, except that one is C# and the other one is VB.Net. C# compiles just fine, but VB.Net throws the warning:

Interfa

2条回答
  •  抹茶落季
    2021-01-06 07:18

    It's bad design to implement both. Have two different child objects which you subscribe to the two observers. I recommend having two child objects, with each implementing one of the interfaces.

    class Beholder
    {
      public IObserver FooObserver{get;private set;}
      public IObserver BarObserver{get;private set;}
    }
    

    When is contra-variance ambiguous?

    Still I don't see an immediate problem here, so the VB.net warning looks indeed strange to me.

    IObserver is contra-variant. So to cause an ambiguity you'd need to find a T such both IObserver and IObserver are IObserver.

    If both Foo and Bar are independent classes, no such T exists, since it's need to derive from both of them, which the .net type system doesn't allow.

    If either of them were an interface, there would be an ambiguity: Just create a class that derives from Foo and implements IBar.

    If one derived from the other, it'd be ambiguous too: if Foo derived from Bar, then IObserver is also IObserver.

    When is co-variance ambiguous?

    And finally with co-variant interfaces, such as IEnumerable it's enough to have a common base class to which both are reference convertible. And Object fulfills this for any two classes(but not value types).

    But IEnumerable would break even without covariance, since you need a consistent implementation of the non generic IEnumerable, and that's not possible for two independent classes.

提交回复
热议问题