typeof 与GetType()的区别

typeof是运算符,获得某一类型的System.Type对象;GetType方法,获取当前实例的类型.

 

一、typeofGetType()的区别

1Typeof是运算符而是方法

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

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

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

5TypeOf():得到一个ClassType

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

 

二、typeofGetType()的实例

 

实例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("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 iinmethodinfo)

            {

                Console.WriteLine(i);//输出Test类的所有方法及继承Object的实例方法

            }

            Console.WriteLine();

            Console.WriteLine();

            Console.WriteLine();

            Console.WriteLine();

            MemberInfo[] memberinfo =type.GetMembers();

           Console.WriteLine(memberinfo.GetType());

            foreach(var iin 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!");

        }

    }

}


 

C# 代码   

GetType():

_2011._12._15.Test

Typeof():

_2011._12._15.Test

System.Reflection.MethodInfo[]

Void speaking()

Voidwriting()

System.TypeGetType()

System.StringToString()

BooleanEquals(System.Object)

Int32GetHashCode()

System.Reflection.MemberInfo[]

Voidspeaking()

Voidwriting()

System.TypeGetType()

System.StringToString()

BooleanEquals(System.Object)

Int32GetHashCode()

Void.ctor()

System.Stringname

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值