gpt4 book ai didi

c# - 为什么此代码会抛出 InvalidOperationException?

转载 作者:太空狗 更新时间:2023-10-29 18:16:16 24 4
gpt4 key购买 nike

我认为我的代码应该使 ViewBag.test 属性等于 "No Match",但它会抛出 InvalidOperationException

这是为什么?

string str = "Hello1,Hello,Hello2";
string another = "Hello5";
string retVal = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.First(p => p.Equals(another));
if (str == another)
{
ViewBag.test = "Match";
}
else
{
ViewBag.test = "No Match"; //this does not happen when it should
}

最佳答案

如你所见here , First 方法在调用它的序列为空时抛出 InvalidOperationException。由于拆分结果中没有元素等于 Hello5,因此结果是一个空列表。在该列表上使用 First 将引发异常。

考虑使用 FirstOrDefault,而不是(记录在 here 中),它不会在序列为空时抛出异常,而是返回可枚举类型的默认值。在这种情况下,调用的结果将为 null,您应该在其余代码中检查这一点。

使用返回 boolAny Linq 方法(已记录 here)可能更简洁。

string str = "Hello1,Hello,Hello2";
string another = "Hello5";
bool retVal = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Any(p => p.Equals(another));
if (retVal)
{
ViewBag.test = "Match";
}
else
{
ViewBag.test = "No Match"; //not work
}

现在必须使用 ternary operator 的一个衬里:

string str = "Hello1,Hello,Hello2";
string another = "Hello5";
ViewBag.test = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Any(p => p == another) ? "Match" : "No Match";

请注意,我在这里还使用了== 来比较字符串,这在C# 中被认为更为惯用。

关于c# - 为什么此代码会抛出 InvalidOperationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16636374/

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