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));//输出: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#中的?使用整理

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值