[英]Can I make this 'if' condition shorter?
I have this condition:我有这个条件:
if (pt.left == anything || pt.left == null || pt.left == borders.left || borders.left == anything)
can I make it shorter?我可以缩短吗? I'm thinking about something like this:我在想这样的事情:
if(pt.left == (anything || null || borders.left) || borders.left == anything)
Is there any way to do it?有什么办法吗?
You could put the elements in an array and use contains.您可以将元素放在数组中并使用 contains。
if((new string[]{anything, null, borders.left}).Contains(pt.left) || borders.left == anything)
or, putting outside the if:或者,放在 if 之外:
var arr = new string[]{anything, null, borders.left};
if(arr.Contains(pt.left) || borders.left == anything)
or, with an extension method:或者,使用扩展方法:
public static class MyExtensions
{
public static bool IsIn<T>(this T obj, params T[] array)
{
return array.Contains(obj);
}
}
Usage:用法:
if(pt.left.IsIn(anything, null, borders.left) || borders.left == anything)
You can clean this up making an extension method:你可以清理这个制作扩展方法:
//I'm assuming you need value equality
public static bool EqualsOneOf<T>(
this T value,
T option1,
T option2,
params T[] options)
where T: IEquatable<T>
{
if (value.Equals(option1))
return true;
if (value.Equals(option2))
return true;
if (options != null && options.Contains(value))
return true;
return false;
}
And now, your expression would be:现在,你的表达是:
if(pt.left.EqualsOneOf(anything, null, borders.left) || borders.left == anything)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.