如何检查该对象是否实现了接口

Mak*_*ach 5 c# inheritance types

鉴于这种情况

interface A {}

class B : A {}

A b = new B();
Run Code Online (Sandbox Code Playgroud)

如何检查对象b是否从界面A创建?

Ste*_*cya 10

尝试使用

if(b is A)
{
    // do something
}
Run Code Online (Sandbox Code Playgroud)

那是你要的吗?


Pon*_*dum 5

你可以像这样测试它:

var b = new B();

var asInterface = x as A;
if (asInterface == null) 
{
    //not of the interface A!
}
Run Code Online (Sandbox Code Playgroud)