gpt4 book ai didi

c# - 有没有更好的方法来编写 new List {"a", "b"}.Contains(str)?

转载 作者:太空宇宙 更新时间:2023-11-03 17:11:50 24 4
gpt4 key购买 nike

我想测试某个字符串是否包含在一个简短的字符串列表中。目前代码是这样的:

if (new List<string> { "A", "B", "C" }.Contains (str)) {

但是,这看起来很臃肿。例如,iirc,在 Java 中我可以简单地编写 {"A", "B", "C"}.Contains(str) ,这比上面的要好得多。

我确信在 C# 中有更好的方法。你能指出来吗?

最佳答案

你可以写一个扩展方法:

public static bool In<T>(this T obj, params T[] candidates)
{
return obj.In((IEnumerable<T>)candidates);
}

public static bool In<T>(this T obj, IEnumerable<T> candidates)
{
if(obj == null) throw new ArgumentNullException("obj");
return (candidates ?? Enumerable.Empty<T>()).Contains(obj);
}

然后您可以使用它来做:

if(str.In("A", "B", "C")) { ... }

关于c# - 有没有更好的方法来编写 new List<string> {"a", "b"}.Contains(str)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1339539/

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