Dom*_*Dom 4 c# extension-methods
在我当前的代码中,我正在使用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 + "]");
}
Run Code Online (Sandbox Code Playgroud)
而不是一个长长的清单else if,我试图凝聚所有的is使用说明Extension Method,但无济于事.
这是我的尝试Extension Method:
public static class Extensions
{
public static bool Is<T>(this T t, params T[] values)
{
return values.Equals(t.GetType());
}
}
Run Code Online (Sandbox Code Playgroud)
和方法:
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 + "]");
}
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么会失败?任何帮助将不胜感激!
您需要传递类型,而不是类名.您还应该使用Contains而不是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)))
{
}
Run Code Online (Sandbox Code Playgroud)
Contains完全匹配类型,因此您可能想要IsSubclassOf或IsAssignableFrom相反
例如
return types.Any(t => t.IsAssignableFrom(obj.GetType()));
Run Code Online (Sandbox Code Playgroud)