c#中GetType()与Typeof()的区别
案例1:
int i = 5;
console.writeline(i.gettype());//system.int32
var x = 127.25m;
console.writeline(x.gettype());//system.decimal
案例2:
namespace _2011._12._15
{
class program
{
static void main(string[] args)
{
test testone = new test();
string s = testone.gettype().tostring();
console.writeline(s);//_2011._12._15.test 命名空间的test类
}
}
class test
{
}
}
typeof()返回的是类名的对象,也可以返回类名,也可以返回特定类内部的方法和字段
namespace _2011._12._15
{
class program
{
static void main(string[] args)
{
test testone = new test();
string s = testone.gettype().tostring();
console.writeline("gettype():");
console.writeline(s);//_2011._12._15.test 命名空间的test类
type type = typeof(test);
console.writeline("typeof():");
console.writeline(type);//_2011._12._15.test 命名空间的test类
console.writeline();
methodinfo[] methodinfo = type.getmethods();
console.writeline(methodinfo.gettype());//system.reflection.methodinfo[]
foreach (var i in methodinfo)
{
console.writeline(i);//输出test类的所有方法及继承object的实例方法
}
console.writeline();
console.writeline();
console.writeline();
console.writeline();
memberinfo[] memberinfo = type.getmembers();
console.writeline(memberinfo.gettype());
foreach(var i in memberinfo)
{
console.writeline(i);//输出test类字段和system.type类型
}
}
}
class test
{
private int age;
public string name;
public void speaking()
{
console.writeline("welcome to cnblog!");
}
public void writing()
{
console.writeline("please writing something!");
}
}
}
运行结果:
gettype():
_2011._12._15.test
typeof():
_2011._12._15.test
system.reflection.methodinfo[]
void speaking()
void writing()
system.type gettype()
system.string tostring()
boolean equals(system.object)
int32 gethashcode()
system.reflection.memberinfo[]
void speaking()
void writing()
system.type gettype()
system.string tostring()
boolean equals(system.object)
int32 gethashcode()
void .ctor()
system.string name