gpt4 book ai didi

C#:测试 int x 是否是给定集合的元素的最优雅方法?

转载 作者:IT王子 更新时间:2023-10-29 04:20:42 25 4
gpt4 key购买 nike

问题:测试是否 x ∉ { 2, 3, 61, 71 }

我经常想知道是否有比以下更好的方法:

if (x != 2 && x != 3 && x != 61 && x != 71)
{
// do things
}

if (!new List<int>{ 2, 3, 61, 71 }.Contains(x))
{
// do things
}

后一个看起来很优雅,但实际上读起来有点烦人,尤其是因为反转。这是一件丑陋的事情,因为在英语中我们说“x 不是...的元素”,这很难在 C# 中表达而不产生刺激性开销。也许有人会说 if (Object(x).IsElementOf(new[] { ... })) 左右?

嗯..有什么建议吗?是否有任何 .Net 标准方法来测试类似的东西?

最佳答案

我使用扩展方法:

using System.Linq;

...

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

...


if (!x.In(2,3,61,71))
...

如果您喜欢这个名称,可以将其重命名为 IsElementOf...

关于C#:测试 int x 是否是给定集合的元素的最优雅方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8228905/

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