简体   繁体   中英

How to check if class “is” an instance of a type given as a variable in C#?

I have the need to do a few checks like this:

if(thisInstance is ThatClass || thisInstance is ThatOtherClass)

I actually won't be needing to do a lot of these, so I could simply write it as it is above, but I'd still prefer doing this in a more tidy way, eg. like this:

Type[] arrayOfClasses = new Type[] { typeof(ThatClass), typeof(ThatOtherClass))}
if(isOfAnyType(thisInstance, arrayOfClasses))

But for some reason I can't get it to work. For some reason even though the string representations of

thisInstance.GetType()

and

typeof(ThatClass)

would be the same,

thisInstance.GetType().IsInstanceOfType(type)

will still always result in false.

In case it makes a difference, this is a Unity project, so if calling one further GetType() for the comparable items (eg. thisInstance.GetType().GetType()) the result is always System.MonoType, in which case the IsInstanceOfType always returns true, which of course isn't useful either.

Any ideas why the comparison fails or how to make it work? Or should I just give up and simply use the "thisInstance is ThatClass" wherever needed?

You could use something like this. The method checks a generic object whether it is of any of the types within the array and returns a bool.

    public static bool IsOfAnyType<T>(T obj, Type[] types)
    {
        bool isOfAnyType = false;

        for (int i = 0; i < classes.Length; i++)
        {
            if (types[i].IsAssignableFrom (obj.GetType()))
            {
                isOfAnyType = true;
                break;
            }
        }
         return isOfAnyType;
      }     

你可以使用isSubclass:

thisInstance.GetType().IsSubclassOf(typeof(ThatClass))

To get your desired way to work you could use this method:

public static bool IsOfAnyType(object obj, Type[] types)
{
    return types.Any(type => type.IsInstanceOfType(obj));
}

If you can't use Linq you can write the method like this:

public static bool IsOfAnyType(object obj, Type[] types)
{
    foreach (var type in types)
    {
        if (type.IsInstanceOfType(obj))
            return true;
    }
    return false;
}

To test this I used this code:

Type[] typesToCheck = { typeof(ThatClass), typeof(ThatOtherClass) };

ThatClass input1 = new ThatClass();
ThatOtherClass input2 = new ThatOtherClass();

if (IsOfAnyType(input1, typesToCheck))
    Console.WriteLine("Hello world from " + input1.GetType());
if (IsOfAnyType(input2, typesToCheck))
    Console.WriteLine("Hello world from " + input2.GetType());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM