c#种GetType()和TypeOf()的区别
C#中任何对象都具有GetType()方法,它的作用和typeof()相同,返回Type类型的当前对象的类型。
typeof(x)中的x,必须是具体的类名、类型名称等,不可以是变量名称;GetType()是基类System.Object的方法,因此只有建立一个实例之后才能够被调用。
Typeof的参数只能是int,string,String,自定义类型,且不能是实例
GetType()
和typeof
都返回System.Type
的引用.
TypeOf()
:得到一个Class
的Type
GetType()
:得到一个Class
的实例的Type
例子:
C#
string s = testone.GetType().ToString();
Type type = typeof(Int32);
使用System.Type.GetType(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName)
能动态得到一个Class
的Type
,避免typeof(Int32)
之类的写法,如果有更简洁的方法望赐教!