C# C语言中If语句的简化#
我有一行代码如下所示:C# C语言中If语句的简化#,c#,if-statement,C#,If Statement,我有一行代码如下所示: 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) 我知道我的例子是不可能的,但有没有办法让它看起来更“干净”?为什么不这样做 bool IsRequestedType(object obj) { if (obj is byte
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)
我知道我的例子是不可能的,但有没有办法让它看起来更“干净”?为什么不这样做
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
我会将其放入一种方法中,使其简化一点:
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);
}
我觉得很好-很好,很清晰。仅限于:
static readonly HashSet<Type> types = new HashSet<Type>
{ typeof(byte), typeof(int), typeof(long) etc };
...
if (types.Contains(obj.GetType())
{
}
静态只读哈希集类型=新哈希集
{typeof(byte)、typeof(int)、typeof(long)等};
...
if(types.Contains(obj.GetType())
{
}
或者使用
obj.GetType().GetTypeCode()
您可以在对象上编写一个扩展方法,为您提供如下语法:
if (obj.Is<byte, int, long>()) { ... }
if(obj.Is()){…}
类似于以下内容(使用多个版本来获得更少或更多的通用参数:
public static bool Is<T1, T2, T3>(this object o)
{
return o is T1 || o is T2 || o is T3;
}
公共静态bool Is(此对象o)
{
返回o为T1 | | o为T2 | | o为T3;
}
创建一个helper函数来放入测试
差不多
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);
}
你打败了我。投票给你。cmon,
如果(真)返回真;否则返回假;
-Ishy。或者简单地说:bool是requestedtype(object obj){返回obj是byte | | obj是int | | obj是long | | obj是decimal | | obj是double | | obj是float;}obj是IComparable的,它还允许字符串…可能不是它想要的。@arkain,这就是我在回答中所做的。@jinguy,还没有向下滚动那么远,当我写的时候,我已经给你投票了。我会将方法命名为IsOneOf,但这确实是一个非常简洁的语法。可惜你不能在泛型中使用类似params的东西parameters@Matthew我想知道如果可以定义接口ITuple
,然后用各种元组通用类将其子类化(元组:ITuple
,元组:ITuple
,等等)。然后重新执行扩展方法,因为是其中的TTuple:ITuple
。然后在该方法中展开泛型类型参数。。这将提供与泛型参数类似的功能…我希望您的语法可用。:-(所有这些黑客行为只是为了让某些东西表现得像INumericIt一样,不一定只针对数字类型,我还需要与自定义类型进行比较。
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