欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#中GetType()与Typeof()的区别

程序员文章站 2023-12-18 18:57:22
案例1:复制代码 代码如下:int i = 5;console.writeline(i.gettype());//system.int32var x = 127.25m;c...

案例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

上一篇:

下一篇: