C# inheritance in generics question

后端 未结 3 962
清歌不尽
清歌不尽 2021-01-18 03:14

I have two interfaces:

public interface A { 
 void aMethod(); 
}


public interface B : A {
 void bMethod();
} 

Later I\'m basically using

3条回答
  •  猫巷女王i
    2021-01-18 03:36

    I don't think you're going to find a way around your problem because the thinking behind it seems flawed. To illustrate, let's create another interface:

    public interface C : A
    {
        void cMethod();
    }
    

    Now, let's use your code:

    Dictionary dict = new Dictionary();
    

    What happens when I try the following?

    C c = new ClassThatImplementsC(); 
    dict.Add(1, c);
    

    Take a look at Eric Lippert's Covariance and Contravarience FAQ for many, many more details.

提交回复
热议问题