我想测试某个字符串是否包含在一个简短的字符串列表中。目前代码是这样的:
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")) { ... }
我是一名优秀的程序员,十分优秀!