C# Generics and polymorphism: an oxymoron?

前端 未结 6 1625
日久生厌
日久生厌 2020-12-16 12:17

I just want to confirm what I\'ve understood about Generics in C#. This has come up in a couple code bases I\'ve worked in where a generic base class is used to create type

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 12:38

    I think you are misunderstanding the point of generics. Generics allows you to generalise a class that requires a type, but doesn't particularly care itself what type that is. For instance, a List is a list of strings, but what would a List be? It's a rather useless concept to have a list of nothing.

    Each specialised class (ie, List) is it's own distinct type, and the compiler treats it as such. It is possible to get at the generic type itself (typeof(List<>) for instance), but in most cases it's useless, and you certainly can't make an instance of it.

提交回复
热议问题