[英]Using typeof as a generic type argument
According to the documentation of typeof : 根据typeof的文件:
[...] To obtain the run-time type of an expression, you can use the .NET Framework method
GetType
[...]要获取表达式的运行时类型,可以使用.NET Framework方法
GetType
Therefore, this means that typeof
must be a compile-time expression. 因此,这意味着
typeof
必须是编译时表达式。
In the article about Generic Type Parameters , it is stated that: 在关于通用类型参数的文章中,声明:
[...] The type argument for this particular class can be any type recognized by the compiler.
[...]此特定类的类型参数可以是编译器可识别的任何类型。
Any type recognized by the compiler is any type inferred by the compiler, ie any type that is known at compile time . 编译器识别的任何类型都是编译器推断的任何类型,即编译时已知的任何类型。
If this is true, then why does the following statement is not allowed? 如果这是真的,那么为什么不允许以下语句?
int value = GenericMethod<typeof(int)>();
typeof() returns a Type object, just like .GetType() would, it cannot be used in place of a type. typeof()返回一个Type对象,就像.GetType()一样,它不能用来代替一个类型。 What you could do though is put
<T>
after your class name, then: 你可以做的是将
<T>
放在你的班级名后,然后:
T value = GenericMethod<T>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.