C#:如何使用类似类型的变量-非通用

时间:2019-02-26 20:32:53

标签: c# types

假设我有一个动物类,以及几个子类,如狗,猫,鸟等。

现在我有一个拥有动物的人。她想看看宠物店是否有同类型的动物。

所以我有

Animal sampleAnimal;
List<Animal> listOfAnimals;  // in our hypothetical pet store

当我尝试执行此操作时(在C#3.5中):

Type typeWeWant = sampleAnimal.GetType();
foreach (var x in listOfAnimals) {
  if (x is typeWeWant) { // error here
     return true;
  }
}

我收到错误消息“ typeWeWant是一个变量,但像类型一样使用。”

好的。我该怎么做?

请记住,我们的人员可能拥有CalicoCat,它是Cat的子类,应该与Cat匹配。因此,使用GetType.ToString()将不起作用。 (在我看来,宠物不是完全发生了什么-如果编写的代码行得通,我会很好的。我不需要同时测试两种方法。)

很抱歉,是否已经有人问过这个问题,但我所能找到的只是有关泛型的问题,

编辑:非常感谢您的回答和“重复”链接!这些正是我需要的,找不到的!

4 个答案:

答案 0 :(得分:4)

您可以按以下方式使用Type.IsAssignableFrom

if (typeWeWant.IsAssignableFrom(x.GetType()))
    return true;

这涵盖了子类和类型相等的情况。

答案 1 :(得分:2)

在if条件下,使用

if (x.GetType() == typeWeWant)

或者,如果您需要查找所有类型的猫,包括猫的子类

if (typeWeWant.IsSubclassOf(x.GetType())
if (x.GetType().IsSubclassOf(typeWeWant)

答案 2 :(得分:1)

您可以执行以下操作:

Type typeWeWant = sampleAnimal.GetType();
foreach (var x in listOfAnimals) {
  // with check only by type of typeWeWant
  if (x.GetType() == typeWeWant) {
     return true;
  }
  // depends on your needs you can use one of following
  // will check if typeWeWant is subclass of x
  if (typeWeWant.IsSubclassOf(x.GetType()) {
     return true;
  }
  // will check if x is subclass of typeWeWant
  if (x.GetType().IsSubclassOf(typeWeWant)) {
     return true;
  }
}

答案 3 :(得分:-1)

玩了一下,这就是我正在工作的:

 Type typeWeWant = sampleAnimal.GetType();
 foreach (var x in listOfAnimals)
 {
     if (typeWeWant.IsInstanceOfType(x))
     {
         return true;
     }
 }

这也有效:

Type typeWeWant = sampleAnimal.GetType();
foreach (var x in listOfAnimals)
{
    if (typeWeWant.IsSubclassOf(x.GetType()))
    {
        return true;
    }
}