处理多个"Is"语句的方法

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)

有谁知道为什么会失败?任何帮助将不胜感激!

Lee*_*Lee 9

您需要传递类型,而不是类名.您还应该使用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完全匹配类型,因此您可能想要IsSubclassOfIsAssignableFrom相反

例如

return types.Any(t => t.IsAssignableFrom(obj.GetType()));
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这有一些不同的行为 - 您需要使用`type.IsAssignableFrom`来获得与当前`is`基于版本相同的行为. (2认同)
  • 实际上,我_think_`IsAssignableFrom`用法在这里是倒退的.我_think_你想要`t.IsAssignableFrom(obj.GetType())`.编辑:而且,如果Dom愿意写它们,你_could_创建一系列泛型重载,所以你可以调用它像`obj.IsAny <SolidColorBrush,LinearGradientBrush,GradientBrush,RadialGradientBrush>()`并避免所有`typeof` in电话. (2认同)