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

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

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


当前回答

我更喜欢的是

也就是说,如果你使用的是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
  }
}

其他回答

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

我更喜欢的是

也就是说,如果你使用的是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
  }
}

我有一个要比较的Type属性,无法使用它(例如my_Type是_BaseTypetoLookFor),但我可以使用这些属性:

base_type.IsInstanceOfType(derived_object);
base_type.IsAssignableFrom(derived_type);
derived_type.IsSubClassOf(base_type);

请注意,在比较相同类型时,IsInstanceOfType和IsAssignableFrom返回true,其中IsSubClassOf将返回false。IsSubclassOf不适用于接口,而其他两个则适用

public class Animal {}
public interface ITrainable {}
public class Dog : Animal, ITrainable{}

Animal dog = new Dog();

typeof(Animal).IsInstanceOfType(dog);     // true
typeof(Dog).IsInstanceOfType(dog);        // true
typeof(ITrainable).IsInstanceOfType(dog); // true

typeof(Animal).IsAssignableFrom(dog.GetType());      // true
typeof(Dog).IsAssignableFrom(dog.GetType());         // true
typeof(ITrainable).IsAssignableFrom(dog.GetType()); // true

dog.GetType().IsSubclassOf(typeof(Animal));            // true
dog.GetType().IsSubclassOf(typeof(Dog));               // false
dog.GetType().IsSubclassOf(typeof(ITrainable)); // false

这取决于我在做什么。如果我需要bool值(例如,确定是否将强制转换为int),我将使用is。如果我确实出于某种原因需要该类型(例如,传递给其他方法),我会使用GetType()。

我发现,通过以下方法检查某个事物的类型是否等于某个事物:

variableName.GetType()==typeof(int)