我见过很多人使用以下代码:

Type t = obj1.GetType();
if (t == typeof(int))
    // Some code here

但我知道你也可以这样做:

if (obj1.GetType() == typeof(int))
    // Some code here

或者这个:

if (obj1 is int)
    // Some code here

就我个人而言,我觉得最后一个是最干净的,但我有什么遗漏吗?哪一个最好用,还是个人喜好?


当前回答

如果您使用的是C#7,那么是时候更新Andrew Hare的伟大答案了。模式匹配引入了一个很好的快捷方式,它在if语句的上下文中为我们提供了一个类型化变量,而不需要单独的声明/强制转换和检查:

if (obj1 is int integerValue)
{
    integerValue++;
}

对于像这样的单一演员来说,这看起来很乏味,但当你有很多可能的类型进入你的日常生活时,这真的很有魅力。以下是避免两次铸造的旧方法:

Button button = obj1 as Button;
if (button != null)
{
    // do stuff...
    return;
}
TextBox text = obj1 as TextBox;
if (text != null)
{
    // do stuff...
    return;
}
Label label = obj1 as Label;
if (label != null)
{
    // do stuff...
    return;
}
// ... and so on

尽可能缩小这段代码,以及避免同一对象的重复强制转换一直困扰着我

switch (obj1)
{
    case Button button:
        // do stuff...
        break;
    case TextBox text:
        // do stuff...
        break;
    case Label label:
        // do stuff...
        break;
    // and so on...
}

编辑:根据Palec的评论,更新了较长的新方法以使用开关。

其他回答

可以在C#中使用“typeof()”运算符,但需要使用System.IO调用命名空间;如果要检查类型,必须使用“is”关键字。

1.

Type t = typeof(obj1);
if (t == typeof(int))

这是非法的,因为typeof只适用于类型,而不适用于变量。我假设obj1是一个变量。这样,typeof是静态的,它在编译时而不是运行时工作。

2.

if (obj1.GetType() == typeof(int))

如果obj1完全是int类型,则为true。如果obj2从int派生,则if条件将为false。

3.

if (obj1 is int)

如果obj1是一个int,或者它派生自一个名为int的类,或者它实现了一个称为int的接口,这就是真的。

我更喜欢的是

也就是说,如果你使用的是is,你很可能没有正确使用继承。

假设那个人:实体,那个动物:实体。Feed是Entity中的一种虚拟方法(让Neil开心)

class Person
{
  // A Person should be able to Feed
  // another Entity, but they way he feeds
  // each is different
  public override void Feed( Entity e )
  {
    if( e is Person )
    {
      // feed me
    }
    else if( e is Animal )
    {
      // ruff
    }
  }
}

相当地

class Person
{
  public override void Feed( Person p )
  {
    // feed the person
  }
  public override void Feed( Animal a )
  {
    // feed the animal
  }
}

用于获取类型的System.Type对象。表达式类型采用以下形式:

System.Type type = typeof(int);

Example:

    public class ExampleClass
    {
       public int sampleMember;
       public void SampleMethod() {}

       static void Main()
       {
          Type t = typeof(ExampleClass);
          // Alternatively, you could use
          // ExampleClass obj = new ExampleClass();
          // Type t = obj.GetType();

          Console.WriteLine("Methods:");
          System.Reflection.MethodInfo[] methodInfo = t.GetMethods();

          foreach (System.Reflection.MethodInfo mInfo in methodInfo)
             Console.WriteLine(mInfo.ToString());

          Console.WriteLine("Members:");
          System.Reflection.MemberInfo[] memberInfo = t.GetMembers();

          foreach (System.Reflection.MemberInfo mInfo in memberInfo)
             Console.WriteLine(mInfo.ToString());
       }
    }
    /*
     Output:
        Methods:
        Void SampleMethod()
        System.String ToString()
        Boolean Equals(System.Object)
        Int32 GetHashCode()
        System.Type GetType()
        Members:
        Void SampleMethod()
        System.String ToString()
        Boolean Equals(System.Object)
        Int32 GetHashCode()
        System.Type GetType()
        Void .ctor()
        Int32 sampleMember
    */

此示例使用GetType方法确定用于包含数值计算结果的类型。这取决于生成的数字的存储要求。

    class GetTypeTest
    {
        static void Main()
        {
            int radius = 3;
            Console.WriteLine("Area = {0}", radius * radius * Math.PI);
            Console.WriteLine("The type is {0}",
                              (radius * radius * Math.PI).GetType()
            );
        }
    }
    /*
    Output:
    Area = 28.2743338823081
    The type is System.Double
    */
if (c is UserControl) c.Enabled = enable;