Why a generic type definition implemented interfaces lose type information?

╄→гoц情女王★ 提交于 2019-12-01 15:57:59

The following types are all different and not connected by an inheritance relationship:

  • IList<T>
  • IList<int>
  • IList<string>

All of these have different Type objects because you can do different things with them. The latter two are the specializations of the former. The first is the generic type definition (which you can obtain through GetGenericTypeDefinition).

There is another part to the explanation. When you say class List<T> : IList<T> then the IList<T> part is not equal to typeof(IList<>) because it is already specialized to T. This is no longer a generic type definition. It is a concrete type such as IList<int>. It is specialized to bind its only type argument to the T that List<T> was specialized to.


Experiment for LINQPad:

Type bound = new List<string>().GetType().GetInterface("IList`1");
bound.GenericTypeArguments.Single().Dump(); //string


Type bound = typeof(List<>).GetInterface("IList`1");
bound.GenericTypeArguments.Single().Dump(); //"T"
(bound.GenericTypeArguments.Single() == typeof(List<>).GetGenericArguments().Single()).Dump(); //true

The first version of IList<T> is the actual typed version of IList<T>, let's say IList<string>.

The second one is the generic definition of IList<T> without a type for T.

That makes the two interfaces different. There are not the same, since the first is a concrete version of the second.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!