typeof,GetType

时间:2023-03-10 01:47:26
typeof,GetType

typeof:

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

Int32 t = new Int32();

Type t = typeof(int);

GetType:

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

int i = 10;

Console.WriteLine(i.GetType());

区别:

GetType()是基类System.Object的方法,因此只有建立一个实例之后才能够被调用(初始化以后)

Typeof()的参数只能是int,string,String,自定义类型,且不能是实例

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

TypeOf() 和GetType()的区别:

(1)TypeOf():得到一个Class的Type

(2)GetType():得到一个Class的实例的Type