Skip to main content
 首页 » 编程设计

c#之检查动态对象是否具有 Foo 的基础

2024年02月20日12me-sa

我们有这两个类

class Foo{ 
    public Foo(){} 
} 
 
class FooBar : Foo{ 
    public FooBar : base() {} 
} 

我知道你可以看看动态对象的类型是不是类似

dynamic bar = new FooBar(); 
bool isType = bar is FooBar; 

但是我如何检查 bar 是否是 foo 类型呢?

如在

dynamic bar = new FooBar(); 
//This would need to check the base as well 
bool isType = bar is Foo; 

或者这已经有效了吗?

请您参考如下方法:

是的,那已经可以工作了。 is 只是检查对象是否可以转换为给定类型。请参阅其上的文档 here .