本文介绍了条件运算符快捷方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尊敬的专家,
最多只需1分钟。我需要在if语句中创建一个多条件OR语句。我知道我可以或他们分开,但有一条捷径。这是我失败的尝试:
Dear experts,
This will only take you 1 min max. I need to make a multiple conditional OR statement in a if statement. I know I can or them seperately, but is there a shortcut. This is my failed attempt:
if (value == (6 || 8 || 10))
{
size1 = value;
}
推荐答案
private enum MySet
{
Six = 6
,
Eight = 8
,
Ten = 10
}
if ( System.Enum.IsDefined ( typeof(MySet) , i ) )
if ((value | 6 | 8 | 10) == (6 | 8 | 10) && value != 0)
{
size1 = value;
}
在这种情况下,您的病情长度没有太大差异。如果你有长名称的变量,或者可能有很多选项,这是一个较短的条件。
另外,你可以写一个 [] object
s:
In this case, there''s no many difference in length of your condition. If you''ve variables with long names, or if many options are possible, this is a shorter condition.
Alternatively, you can write an extension method[^] for object
s:
public static class MultipleOrConditionClass
{
public static bool MultipleOrCondition(this object obj, params object[] objectsToCompare)
{
return objectsToCompare.Contains(obj);
}
}
现在,请使用以下条件:
Now, use this condition:
if (value.MultipleOrCondition(6, 8, 10))
{
size1 = value;
}
希望这会有所帮助。
Hope this helps.
这篇关于条件运算符快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!