我有一行代码如下:
if (obj is byte || obj is int || obj is long || obj is decimal || obj is double || obj is float)
Run Code Online (Sandbox Code Playgroud)
是否有可能写出比这更优雅的东西?就像是:
if (obj is byte, int, long)
Run Code Online (Sandbox Code Playgroud)
我知道我的例子是不可能的,但有没有办法让这个看起来"更干净"?
Jas*_*son 27
您可以在对象上编写扩展方法,为您提供如下语法:
if (obj.Is<byte, int, long>()) { ... }
Run Code Online (Sandbox Code Playgroud)
像这样的东西(使用多个版本用于更少或更多的通用参数:
public static bool Is<T1, T2, T3>(this object o)
{
return o is T1 || o is T2 || o is T3;
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 12
只要:
static readonly HashSet<Type> types = new HashSet<Type>
{ typeof(byte), typeof(int), typeof(long) etc };
...
if (types.Contains(obj.GetType())
{
}
Run Code Online (Sandbox Code Playgroud)
或者使用obj.GetType().GetTypeCode().
我会把它扔进一个方法来简化它:
private static bool ObjIsNumber(object obj)
{
return (obj is byte || obj is int || obj is long ||
obj is decimal || obj is double || obj is float);
}
Run Code Online (Sandbox Code Playgroud)