How to check that object implements interface
Given this scenario
interface A {}
class B : A {}开发者_如何学Go
A b = new B();
How can I check that object b is created from interface A?
Try to use is
if(b is A)
{
// do something
}
is that what you want?
You could do test it like this:
var b = new B();
var asInterface = x as A;
if (asInterface == null)
{
//not of the interface A!
}
IS and AS.
We found it practical to use the following:
IMyInterface = instance as IMyInterface;
if (intance != null)
{
//do stuff
}
'as' is the faster than 'is', also is saves a number of casts - if your instance impelments IMyInterface, you'll need no more casts.
精彩评论