(开放通用类型)没有指定参数的通用类型 [英] (open generic type) typeof generic type with no parameters specified
问题描述
有人可以在没有指定具体参数的情况下向我解释 typeof(SomeGenericType<>
)的C#语言需求.
我整理了以下示例:
var t1 = typeof(Nullable<>);var t2 = typeof(Nullable< int>);var q = 1 as int ?;var b1 = t1.IsInstanceOfType(q);//错误的var b2 = t2.IsInstanceOfType(q);//真的
我首先想到 typeof(Nullable<>)
比 t2
更通用,后者指定了通用参数 int
,但是 b1
原来是 false
-因此, int?
的实例不是 Nullable<>
的实例.>
那么应该如何将 b1
定义为 true
的变量?它有什么实际用途?
那么应该如何为b1定义一个变量呢?
不能.(实际上,使用 Nullable< T>
还是会遇到有趣的拳击问题,但是我们可以...)
在执行时,值始终是 closed 类型的实例. Nullable<>
, List<>
是 open 通用类型.在这种类型上调用 IsInstanceOfType
从来没有用.但这并不意味着它没用.
通常在反射中使用开放类型.例如:
public IList CreateList(Type elementType){类型closeType = typeof(List<>).MakeGenericType(elementType);返回(IList)Activator.CreateInstance(closedType);}
可能有较高的代码,而是通用的,但是调用较低的级别时传递的是 Type
值-然后列表可以返回堆栈并进行强制转换到 IEnumerable< T>
以获取 T
的适当值.
同样,您可能希望创建一个带有反射的封闭类型以在其上调用方法,等等.
您还可以 使用它来查找特定类型是否为 some 类型实参实现了通用接口-对于实现的每个接口,您都可以查明它是否通用,获取通用类型定义,然后查看其是否等于(例如) IEnumerable<>
.
Can somebody explain me the need in C# language for typeof(SomeGenericType<>
), with no concrete parameters specified.
I put together the following example:
var t1 = typeof(Nullable<>);
var t2 = typeof(Nullable<int>);
var q = 1 as int?;
var b1 = t1.IsInstanceOfType(q); //false
var b2 = t2.IsInstanceOfType(q); //true
I first thought typeof(Nullable<>)
is "more generic" than t2
, which specifies generic parameter int
, but b1
turns out to be false
- so instance of int?
is not instance of Nullable<>
.
So how a variable should be defined for b1
to be true
? what practical uses does it have?
So how a variable should be defined for b1 to be true?
It can't. (In fact, with Nullable<T>
you'll run into interesting boxing problems anyway, but there we go...)
At execution time, values are always instances of closed types. Nullable<>
, List<>
are open generic types. It's never useful to call IsInstanceOfType
on such a type. That doesn't mean it's useless though.
Typically open types are used in reflection. For example:
public IList CreateList(Type elementType)
{
Type closedType = typeof(List<>).MakeGenericType(elementType);
return (IList) Activator.CreateInstance(closedType);
}
There can be code high up which is generic, but calls into lower levels passing in Type
values instead - the list could then go back up the stack and be cast to IEnumerable<T>
for the appropriate value of T
.
Likewise you may want to create a closed type with reflection to call a method on it, etc.
You can also use it to find out whether a particular type implements a generic interface for some type argument - for each interface implemented, you can find out if it's generic, get the generic type definition, and see whether that's equal to (say) IEnumerable<>
.
这篇关于(开放通用类型)没有指定参数的通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!