我经历了Asp.Net MVC lesson次,了解到,对于一种符合控制器操作资格的方法,
- 它不能有"open generic type"
我对泛型有点了解,并在一定程度上使用了它们,但是:
- 什么是open generic type英寸.网
- 有"closed generic type"这个词吗?
- Open generic type是一个不常使用的术语.它使用了什么/与之混淆了什么?
我经历了Asp.Net MVC lesson次,了解到,对于一种符合控制器操作资格的方法,
我对泛型有点了解,并在一定程度上使用了它们,但是:
C#语言将开放类型定义为类型参数或使用未知类型参数定义的泛型类型:
所有类型都可以分为开放类型或封闭类型.open type是一种涉及类型参数的类型.更具体地说:
- 类型参数定义开放类型.
- 数组类型是开放类型当且仅当其元素类型是开放类型时.
- 当且仅当constructed type的一个或多个类型参数是open type时,constructed type才是开放类型.当且仅当constructed nested type的一个或多个类型参数或其包含类型的类型参数是开放类型时,constructed nested type才是开放类型.
closed type是一种不是开放式的类型.
因此,T
、List<T>
、Dictionary<string,T>
和Dictionary<T,U>
都是开放类型(T
和U
是类型参数),而List<int>
和Dictionary<string,int>
是封闭类型.
有一个相关的概念:ANunbound generic type是具有未指定类型参数的泛型类型.未绑定类型不能在typeof()
以外的表达式中使用,并且不能实例化它或调用它的方法.例如,List<>
和Dictionary<,>
是未绑定类型.
要澄清开放式类型和未绑定类型之间的细微区别,请执行以下操作:
class Program {
static void Main() { Test<int>(); }
static void Test<T>() {
Console.WriteLine(typeof(List<T>)); // Print out the type name
}
}
如果你运行这个片段,它会打印出来
System.Collections.Generic.List`1[System.Int32]
这是List<int>
的CLR名称.很明显,在运行时,类型参数是System.Int32
.这使得List<T>
成为bound开放式.
在运行时,您可以使用反射将类型参数绑定到未绑定泛型类型的未指定类型参数,并使用Type.MakeGenericType
method:
Type unboundGenericList = typeof(List<>);
Type listOfInt = unboundGenericList.MakeGenericType(typeof(int));
if (listOfInt == typeof(List<int>))
Console.WriteLine("Constructed a List<int> type.");
您可以判断类型是否为未绑定泛型类型(generic type definition),从中可以使用Type.IsGenericTypeDefinition
property构造绑定类型:
Console.WriteLine(typeof(Dictionary<,>).IsGenericTypeDefinition); // True
Console.WriteLine(typeof(Dictionary<int,int>).IsGenericTypeDefinition); // False
要在运行时从构造的类型获取未绑定的类型,可以使用Type.GetGenericTypeDefinition
method.
Type listOfInt = typeof(List<int>);
Type list = listOfInt.GetGenericTypeDefinition(); // == typeof(List<>)
请注意,对于泛型类型,可以具有完全未绑定的类型定义,也可以具有完全绑定的定义.您不能绑定某些类型参数而不绑定其他类型参数.例如,你不能有Dictionary<int,>
或Dictionary<,string>
.