可以在C#的if-else语句中定义类似'between'之类的东西吗?

Sna*_*yes 12 c#

我想问一个在C#中比我有更强技能的人.

是否可以减少以下代码

if(val > 20 && val < 40 )
...
else
if(val > 40 && val < 72 )
...
else
if(val > 72 && val < 88 )
...
else
...
Run Code Online (Sandbox Code Playgroud)

我们假设我有10-11个if-else语句.

缩短上述代码的最佳方法是什么?

我想像between在sql 中的东西.

Ada*_*dam 28

定义扩展方法:

public static bool Between(this int source, int a, int b)
{
    return source > a && source < b;
}
Run Code Online (Sandbox Code Playgroud)

然后,使用它:

if (val.Between(20, 40))
//...
Run Code Online (Sandbox Code Playgroud)

正如o comment在他的评论中正确指出的那样,你可以更进一步,IComparable<T>并通过一般的扩展方法支持所有实现者:

public static bool Between<T>(this T source, T a, T b) where T : IComparable<T>
{
    return source.CompareTo(a) > 0 && source.CompareTo(b) < 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 你可以把它作为一个通用的扩展方法:`public static bool Between <T>(this T source,T a,T b):where T:IComparable <T>` (12认同)