C# inheritance in generics question

后端 未结 3 944
清歌不尽
清歌不尽 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条回答
  •  南方客
    南方客 (楼主)
    2021-01-18 03:51

    Nope it's a covariance issue. If you could do:

    Dictionary dict = new Dictionary();
    

    It would be possible without a compiler error to put an object of Type A in dict.

    The problem is that dict looks like: Dictionary but it is really type Dictionary() (so placing an object of Type A would throw a runtime error because of an invalid cast), so you shouldn't be allowed to even try to place an object of Type A in dict, which is why you can't do :

    Dictionary dict = new Dictionary();
    

    It's protecting you from making a runtime mistake.
    You want to check out Eric Lippert's blog on the subject: http://blogs.msdn.com/b/ericlippert/

    It's one of his favorite topics to talk about, so it's quite thorough.

提交回复
热议问题