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

Florida ·
更新时间:2024-11-10
· 741 次阅读

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

您可能感兴趣的文章:javascript typeof的用法与typeof运算符介绍[详细]HTML DOM的nodeType值介绍js判断undefined变量类型使用typeofJs nodeType 属性全面解析nodeType属性返回被选节点的节点类型介绍js中typeof的用法汇总使用typeof方法判断undefined类型浅谈nodeName,nodeValue,nodeType,typeof 的区别



C# typeof

需要 登录 后方可回复, 如果你还没有账号请 注册新账号