C#中typeof关键字如何用于实现类型检查

avatar
作者
猴君
阅读量:0

在C#中,typeof关键字用于获取一个类型的Type对象。通过使用typeof关键字,可以在运行时动态地检查一个对象的类型。下面是一个示例:

using System;  class Program {     static void Main()     {         object obj = 42;          if (obj.GetType() == typeof(int))         {             Console.WriteLine("obj is an int");         }         else         {             Console.WriteLine("obj is not an int");         }     } } 

在上面的示例中,我们使用了GetType()方法获取obj对象的类型,并使用typeof(int)来检查obj是否是int类型。如果obj是int类型,则输出"obj is an int",否则输出"obj is not an int"。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!