共用方式為


Does this object subclass X or implement Y?

A guy on my team dropped by to ask me how to do this, so I figured it'd be worth posting about.

The situation in his case is that he had an object passed into a method he was writing and he wanted to check if it implemented a particular interface, something like:

 bool CheckForInterface(Type interfaceType, object objectToCheck)
{
    // mystery code goes here
}

He knew that he couldn't just do "objectToCheck is interfaceType" (since interfaceType is a runtime instance of the type, not a compile-time declaration of the interface itself).

Given what we was trying to accomplish, I told him the method he was looking for was Type.IsAssignableFrom which makes this a single-line implementation.

     static bool CheckType1(Type lookingForThisType, object objectToCheck)
    {
        return lookingForThisType.IsAssignableFrom(objectToCheck.GetType());
    }

However, I told him in this case, I'd recommend keeper it simpler and sticking with using "is" instead, since IMHO that's more recognizable and simpler for the reader to quickly realize what's going on.  This just means you need a generic parameter, which gives you the added benefit that you could add compile-time constraints on the type, but it's also clearly not as useful if you need to do a check against a dynamic type.

     static bool CheckType2<T>(object objectToCheck)
    {
        return objectToCheck is T;
    }

In any case, here's both and a quick proof that they both work fine for this particular task:

 using System;

interface IFoo { }
class Blah { }
class Bar : IFoo { }

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("IsAssignableFrom: {0}", CheckType1(typeof(IFoo), new Blah()));
        Console.WriteLine("IsAssignableFrom: {0}", CheckType1(typeof(IFoo), new Bar()));
        Console.WriteLine("is: {0}", CheckType2<IFoo>(new Blah()));
        Console.WriteLine("is: {0}", CheckType2<IFoo>(new Bar()));
    }

    static bool CheckType1(Type lookingForThisType, object objectToCheck)
    {
        return lookingForThisType.IsAssignableFrom(objectToCheck.GetType());
    }

    static bool CheckType2<T>(object objectToCheck)
    {
        return objectToCheck is T;
    }
}
  

Comments