检查对象类型是否继承了抽象类型 [英] Check if objects type inherits an abstract type

查看:33
本文介绍了检查对象类型是否继承了抽象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个对象,someDrink.它可以是 CocaColaPepsi 类型,它们都继承了抽象的 Cola(继承了 Drink)或任何类型的饮料.我有一个方法可以返回一串最喜欢的饮料.

Say I have an object, someDrink. It could be of type CocaCola or Pepsi which both inherit the abstract Cola (which inherits Drink) or any kind of drink for that matter. I have a method that returns a string of the most preferred beverage.

public string PreferredDrink(Drink someDrink)
{
    var orderOfPreference = new List<Type> {
        typeof (Cola),
        typeof (PurpleDrank),
        typeof (LemonLimeBitters)
        ...
    }

    foreach (drinkType in orderOfPreference) {
        if (someDrink.GetType() == drinkType) {
            return someDrink.ToString()
        }
    }

    throw new Exception("Water will be fine thank you");
}

上面的代码是行不通的,因为someCola 的类型永远不可能等于一个抽象类型.理想情况下,我想做类似的事情:

The code above will not work, because the type of someCola can never be equal to an abstract type. Ideally I would like to do something like:

if (someCola is drinkType) ...

但是 is 关键字只允许在它后面有一个类名.

But the is keyword only allows a class name after it.

是否有其他方法可以检查 someDrink 是否继承给定类型?

Is there another way to check if someDrink inherits a given type?

如果您能提出更好的方法来执行此操作,则重构并非完全不可能.

Refactoring isn't totally out of the question if you can suggest a better way to do this.

推荐答案

当然 - 您可以使用 Type.IsAssignableFrom:

Sure - you can use Type.IsAssignableFrom:

if (drinkType.IsAssignableFrom(someDrink.GetType()))

请注意,不要以错误的方式获取调用的目标和参数,这一点很重要.我每次使用它时都必须查阅文档,幸运的是这种情况很少:)

Note that it's important that you don't get the target of the call and the argument the wrong way round. I have to consult the docs every time I use it, which is fortunately rarely :)

这篇关于检查对象类型是否继承了抽象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆