gpt4 book ai didi

c# - 简化 if 语句

转载 作者:行者123 更新时间:2023-12-02 14:33:55 28 4
gpt4 key购买 nike

只是一个基本的if声明,试图使其更简单、更易于阅读。现在它是:

  if ( myid == 1 || myid ==2 || myid == 10 || myid == 11 || myid == 12 || myid == 13 || myid ==14 || myid ==15)
{
...
}

我在想类似int[] ints = [1,2,10,11,12,13,14,15]的东西,那么

  if (ints.Contains(myid))
{
}

我实际上不知道这是否真的更容易阅读,它肯定更短,两者的性能差异可能可以忽略不计。

最佳答案

问题是基于意见的,但如果可读性是关键因素,一个选择是使用扩展方法

public static bool In<T>(this T x, params T[] set)
{
return set.Contains(x);
}

这将允许你写:

if (myid.In(1, 2, 10, 11, 12, 13, 14, 15))
{

}

我将填写其他选项,只是为了给出一些比较的感觉(我当然不提倡接下来的所有选项)

丑陋,但对于一个“连续”序列来说效果很好:

if ((myid >= 1 && myid <= 2) || (myid >= 10 && myid <= 15))
{

}

您可以定义自己的 Between 扩展方法。注意:我总是忘记 minVal 或 maxVal 是包含还是排除。 (例如 Random.Next 使用包含 minValue 且不包含 maxValue):

public static bool Between(this int number, int minVal, int maxVal)
{
return number >= minVal && number <= maxVal;
}

多考虑better Between扩展方法,这只是一个简单的例子。现在您可以:

if (myid.Between(1, 2) || myid.Between(10, 15))
{

}

或者使用 native 方法

if (new[]{1, 2, 10, 11, 12, 13, 14, 15}.Contains(myid))
{

}

或者

int[] expectedValues = {1, 2, 10, 11, 12, 13, 14, 15};
if (expectedValues.Contains(myid))
{

}

关于c# - 简化 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24521759/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com