本文主要是介绍C# Object.GetType()获取对象的类类型/获取类的类型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、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));//输出:TrueConsole.WriteLine(type1 == type2); //输出:TrueConsole.WriteLine(type1 == typeof(Student));//输出:TrueConsole.WriteLine(type1.Name); //输出:StudentConsole.WriteLine(type1.FullName); //输出:Grammar2._1.TypeTest+Student
}
public class Student
{public int ID { get; set; }
}
更多:
C# using 关键字使用整理
C#Nullable<T>可空的值类型,C#中的?使用整理
这篇关于C# Object.GetType()获取对象的类类型/获取类的类型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!