如果C#中的语句简化
我有一行代码如下:
if (obj is byte || obj is int || obj is long || obj is decimal || obj is double || obj is float)
是否有可能写出比这更优雅的东西? 就像是:
if (obj is byte, int, long)
我知道我的例子是不可能的,但有没有办法让这个看起来“更干净”?
您可以在对象上编写扩展方法,为您提供如下语法:
if (obj.Is()) { ... }
像这样的东西(使用多个版本用于更少或更多的通用参数:
public static bool Is(this object o) { return o is T1 || o is T2 || o is T3; }
只要:
static readonly HashSet types = new HashSet { typeof(byte), typeof(int), typeof(long) etc }; ... if (types.Contains(obj.GetType()) { }
或者使用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); }
你为什么不这样做?
bool IsRequestedType(object obj) { if (obj is byte || obj is int || obj is long || obj is decimal || obj is double || obj is float) return true; return false; }
或者你也许可以逃脱
obj is IComparable
这对我来说很好 – 很好也很清楚。
public static bool IsOneOf(object o, params Type[] types) { foreach(Type t in types) { if(o.GetType() == t) return true; } return false; } long l = 10; double d = 10; string s = "blah"; Console.WriteLine(IsOneOf(l, typeof(long), typeof(double))); // true Console.WriteLine(IsOneOf(d, typeof(long), typeof(double))); // true Console.WriteLine(IsOneOf(s, typeof(long), typeof(double))); // false
创建一个帮助函数来测试。
就像是
public static Boolean IsNumeric(Object myObject) { return (obj is byte || obj is int || obj is long || obj is decimal || obj is double|| obj is float); }