在我当前的代码中,我正在使用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 + "]");
}
我没有列出一长串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());
}
}
和方法:
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 + "]");
}
有谁知道为什么会失败?任何帮助将不胜感激!