Frage

Normally, when I want to check if an object is one of these types, I use the following code:

object a = "ABC";

if (a is string || a is int || a is double)
{

}

I want to create an extension method that that shorten this, such as:

if (a.IsOneOfTheseType(string, int, double)
{

}
War es hilfreich?

Lösung

Try this:

public static class ObjectExtensions {
    public static bool IsOneOfTypes(this object o, params Type[] types) {
        Contract.Requires(o != null);
        Contract.Requires(types != null);
        return types.Any(type => type == o.GetType());
    }
}

I don't have a compiler handy to test / check for stupid mistakes but this should get you pretty close. Note that this satisfies your requirement of "check[ing] if an object is one of [some given] types". If you want to check assignability, replace the lambda expression with

type => type.IsAssignableFrom(o.GetType())

See Type.IsAssignableFrom for the exact semantics.

To use:

object a = "ABC";
bool isAStringOrInt32OrDouble =
    a.IsOneOfTypes(typeof(string), typeof(int), typeof(double));

or

object a = "ABC";
bool isAStringOrInt32OrDouble = 
    a.IsOneOfTypes(new[] { typeof(string), typeof(int), typeof(double) });
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top