![](/img/trans.png)
[英]Can `typeof(T).IsAssignableFrom(x.GetType())` be safely rewritten as `x is T`?
[英]What does “Generic Type” mean? in .net : x.GetType().IsGenericType
首先要回答您的两个问题:
Object
。 要确定类型是否为通用类型,只需查看类定义即可。 Queue
不是通用类型,而Queue<T>
是通用类型,因为您可以通过将通用类型参数 T
替换为任何其他类型来获得不同的类型。 例如, Queue<int>
, Queue<string>
, Queue<Object>
等都使用在Queue<T>
类中一次定义的相同代码。 请注意,它们本身也是通用类型。 嵌套在通用类型中的嵌套类型也被视为通用类型。 “基本类型” Queue<T>
被称为通用类型定义 。
public abstract class MyListBase { }
public abstract class MyListBase<T> : MyListBase { }
public class MyList<T> : MyListBase<T>
{
public class Nested { }
}
public class MyStringList : MyList<string> { }
...
var isGenericType0 = typeof(MyListBase).IsGenericType; //False
var isGenericType1 = typeof(MyListBase<>).IsGenericType; //True
var isGenericType2 = typeof(MyListBase<>)
.MakeGenericType(typeof(char)).IsGenericType; //True
var myIntegerList = new MyList<int>();
var isGenericType3 = myIntegerList.GetType().IsGenericType; //True
var myNested1 = new MyList<int>.Nested();
var isGenericType4 = myNested1.GetType().IsGenericType; //True
var myStringList = new MyStringList();
var isGenericType5 = myStringList.GetType().IsGenericType; //False
希望您现在可以绕过泛型类型。
泛型使您可以根据其作用的确切数据类型定制方法,类,结构或接口。
泛型类型定义是用作模板的类,结构或接口声明,带有可包含或使用的类型的占位符。 例如,System.Collections.Generic.Dictionary类可以包含两种类型:键和值。 因为通用类型定义只是模板,所以不能创建作为通用类型定义的类,结构或接口的实例。
public class Generic<T>
{
public T Field;
}
在答案中很难描述什么是.NET中的泛型。 最好阅读文档。
简而言之,它是С++中的模板,Java中的泛型,.NET,Delphi。 此处常见说明
https://zh.wikipedia.org/wiki/Generic_programming
来自MSDN的文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.