简体   繁体   English

C#:条件语句中一个变量的两次比较的更好语法

[英]C#: Better Syntax for Two Comparisons Of One Variable in a Conditional Statement

Is there a short hand method for handling a two comparisons in a conditional statement? 是否有一种简便的方法可以处理条件语句中的两个比较?

For example: 例如:

if(ReturnedCount > 0 && ReturnedCount < 50)
{
    ...
}

I'm fairly certain that a variable must always be on the left hand side of an operator because when I tried the following it didn't work: 我相当确定变量必须始终位于运算符的左侧,因为当我尝试以下操作时,它不起作用:

if(0 < ReturnedCount < 50)
{
    ...
}

I did a search on google for the c# equivalent of the between keyword in SQL and got no good results. 我在Google上搜索了SQL中ween关键字的C#等效项,但没有得到很好的结果。

Is there a better way to handle this sort of double comparison for the same variable? 对于同一个变量,是否有更好的方法来处理这种双重比较?

Short answer, C# doesn't have any syntax sugar to help, each conditional test just gets added on to the statement. 简短的答案,C#没有任何语法帮助,只是将每个条件测试添加到语句中。

At some point, when it starts getting hard to read, you can break it out into a method call that returns true/false. 在某个时候,当它开始变得难以阅读时,您可以将其分解为一个返回true / false的方法调用。

ie. 即。

if (Pred.Equals( a, b, c, d ))
{ ... }

Where, Pred is a (non existant) static class containing helper methods to be used as logical predicates. 其中,Pred是一个(不存在的)静态类,其中包含用作逻辑谓词的辅助方法。

Alternately... 交替...

A second approach to this is chaining method calls to represent consecutive conditional tests. 第二种方法是链接方法调用,以表示连续的条件测试。

ie. 即。

if (a.GreaterThan(b).LessThan(c).IsTrue())
{...}

Where, GreaterThan and LessThan are extension methods which return either the 'this' value or 'null', and IsTrue returns true if 'this' is non-null. 其中,GreaterThan和LessThan是扩展方法,它们返回'this'值或'null',如果'this'为非null,则IsTrue返回true。

Those are the only two techniques I've come across myself, goodluck! 那是我遇到的仅有的两种技术,祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM