日期:2014-05-18  浏览次数:20440 次

GetType和typeof有什么分别
不太分得清

------解决方案--------------------
XX.GetType() 这个XX是对象

typeof(XX) 这个XX是类型
------解决方案--------------------
GetType是得到它的类型

typeof是转换类型
------解决方案--------------------
假定你有两个类,一个是 Animal,另一个是 Cat,那么:

Animal a = new Cat();
Type t = typeof(Animal); // 返回的对象代表 Animal 类型
t = a.GetType(); // 返回的类型是 a 的运行时类型,也就是 Cate 类型


------解决方案--------------------
typeof: The typeof operator is used to obtain the System.Type object for a type.



运算符,获得某一类型的 System.Type 对象。



Type t = typeof(int);





GetType: Gets the Type of the current instance.



方法,获取当前实例的类型。



int i = 10;

Console.WriteLine(i.GetType());



区别:



Typeof()是运算符而GetType是方法
GetType()是基类System.Object的方法,因此只有建立一个实例之后才能够被调用(初始化以后)
Typeof()的参数只能是int,string,String,自定义类型,且不能是实例



GetType() 和typeof()都返回System.Type的引用。