本文介绍了为什么C#泛型中的专业化有限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对C#的泛型有一个评论:




  • 专业化意味着什么?它是否与具有特定类型参数的泛型类型的实例化不同?

  • 专业化程度有限是什么意思? / b>
  • 为什么它是在泛化发生之前编译泛型类型定义的结果?



解决方案

作者在他的答案的部分内容中解释了致力于Java泛型

换句话说,如果泛型类型参数是特定类型的参数,那么这是一种特殊的功能。当您将类型实例化为 List< bool> 时,为 List List < / code>将是一个专业化的例子。

作者的意思是,尽管你可以写一些东西,如

  if (typeof(T)== typeof(bool)){
...
}

响应类型参数组合的能力是有限的,因为任何关于类型组合的决定都必须在运行时作出。

因为在CLR中完成了泛化,所以在C#编译器不在图片之后。编译器必须为CLR生成一个通用类型定义,作为用于为泛型类实例生成封闭构造类型的模板。


The question "What is reification?" has a comment on C#'s generics:

  • What does it mean by "specialization"? Is it not the same as instantiation of a generic type with a specific type argument?

  • What does it mean by "the degree of specialization is limited"?

  • Why is it "a result of the fact that a generic type definition is compiled before any reification happens"?

解决方案

Author explains in the portion of his answer dedicated to Java generics that

In other words, it is an ability to do something special if a generic type parameter is of a specific type. Supplying an implementation of List<T> that represents individual elements as bits when you instantiate the type as List<bool> would be an example of specialization.

Author means that although you can write things like

if (typeof(T) == typeof(bool)) {
    ...
}

your abilities to respond to a combination of type arguments are limited, because any decision on a type combination has to be made at run-time.

Because reification is done in CLR, well after C# compiler is out of the picture. The compiler must produce a generic type definition for CLR to use as a "template" for making closed constructed types for instances of a generic class.

这篇关于为什么C#泛型中的专业化有限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 00:05