C# Object.GetType()获取对象的类类型/获取类的类型

来源:互联网 发布:屏幕文字识别软件 编辑:程序博客网 时间:2024/05/16 18:24

一、C#获取对象的类类型方式

方式1.所有类隐式继承自Object,然而Object类中的GetType()就可以获取当前对象的类,对应的类型

        //        // 摘要:        //     获取当前实例的 System.Type。        //        // 返回结果:        //     当前实例的准确运行时类型。        [SecuritySafeCritical]        public Type GetType();

方式2,使用typeof关键词

System.Type type3 = typeof(Student);

特别说明:

1.一个类的类型在进程内是唯一的。

2.可以用作线程锁使用

lock (this.GetType()){}
实例验证:

public static void TestOne(){    Student stu1 = new Student() { ID = 1 };    Student stu2 = new Student() { ID = 2 };    //1.获取对象的类的类型    Type type1 = stu1.GetType();    Type type2 = stu2.GetType();    Console.WriteLine(Object.Equals(type1, type2));//输出:True    Console.WriteLine(type1 == type2); //输出:True    Console.WriteLine(type1 == typeof(Student));//输出:True    Console.WriteLine(type1.Name);     //输出:Student    Console.WriteLine(type1.FullName); //输出:Grammar2._1.TypeTest+Student}public class Student{    public int ID { get; set; }}



更多:

C# using 关键字使用整理

C#Nullable<T>可空的值类型,C#中的?使用整理

0 0
原创粉丝点击