In my current code, I am testing for an object's type using if/else if
& is
:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is double)
{
//do something
}
else if (value is int)
{
//do something
}
else if (value is string)
{
//do something
}
else if (value is bool)
{
//do something
}
Type type = value.GetType();
throw new InvalidOperationException("Unsupported type [" + type.Name + "]");
}
Rather than having a long list of else if
, I tried to condense all of the is
statements using an Extension Method
, but to no avail.
Here is my attempt at the Extension Method
:
public static class Extensions
{
public static bool Is<T>(this T t, params T[] values)
{
return values.Equals(t.GetType());
}
}
and the method:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is double)
{
//do something
}
else if (value.Is<object>(int, string, bool))
{
//do something
}
Type type = value.GetType();
throw new InvalidOperationException("Unsupported type [" + type.Name + "]");
}
Does anyone know why this is failing? Any help would be greatly appreciated!
You need to pass it the types, not the class names. You should also use Contains
instead of Equals
:
public static bool IsAny(this object obj, params Type[] types)
{
return types.Contains(obj.GetType());
}
if(value.IsAny(typeof(SolidColorBrush), typeof(LinearGradientBrush), typeof(GradientBrush), typeof(RadialGradientBrush)))
{
}
Contains
matches the type exactly, so you might want to is IsSubclassOf
or IsAssignableFrom
instead
e.g
return types.Any(t => t.IsAssignableFrom(obj.GetType()));
So you have several problems here. The first of which is the line: values.Equals(t.GetType())
. You're not checking each of the values of the collection, you're checking if the collection as a whole is equal to the one type. Since one is an object[]
and one is a Type
they'll never be equal. You need to check if Any of the values in the collection are equal to the type.
Next, you don't want the parameters to be a bunch of objects, you want them to be a bunch of Types.
Here is a better solution:
public static bool IsAny(this object obj, params Type[] types)
{
return types.Any(type => type.IsAssignableFrom(obj.GetType()));
}
You would then use it like:
bool b = "a".IsAny(typeof(int), typeof(double), typeof(MyClass));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With