一、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; }
}
更多: