有人可以向我解释为什么代码的顶部有效,但当测试是一个数组时却不起作用吗?
string test = "Customer - ";
if (test.Contains("Customer"))
{
test = "a";
}
下面的代码不起作用
string[] test = { "Customer - " };
if (test.Contains("Customer"))
{
test[0] = "a";
}
最佳答案
在第一种情况下,您调用 String.Contains
它检查字符串是否包含子字符串。
因此,此条件返回 true
。
在第二种情况下,您调用 Enumerable.Contains
在 string[]
上检查字符串数组是否包含特定值。
由于您的集合中没有 "Customer"
字符串,因此它返回 false
。
这是两种叫法相似但类型不同的方法。
如果你想检查集合中的任何字符串是否包含“Customer”作为子字符串,那么你可以使用LINQ .Any()
:
if (test.Any(s => s.Contains("Customer"))
{
test[1] = "a";
}
关于C# 字符串数组包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44916954/