C# 为什么这段代码会抛出 InvalidOperationException?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16636374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is this code throwing an InvalidOperationException?
提问by user2398766
I think that my code should make the ViewBag.testproperty equal to "No Match", but instead it throws an InvalidOperationException.
我认为我的代码应该使ViewBag.test属性等于"No Match",但它会抛出一个InvalidOperationException.
Why is this?
为什么是这样?
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
}
采纳答案by Ben Reich
As you can see here, the Firstmethod throws an InvalidOperationExceptionwhen the sequence on which it is called is empty. Since no element of the result of the split equals Hello5, the result is an empty list. Using Firston that list will throw the exception.
正如您在此处看到的,该First方法InvalidOperationException在调用它的序列为空时抛出 an 。由于拆分结果的任何元素都不等于Hello5,因此结果是一个空列表。First在该列表上使用将引发异常。
Consider using FirstOrDefault, instead (documented here), which, instead of throwing an exception when the sequence is empty, returns the default value for the type of the enumerable. In that case, the result of the call will be null, and you should check for that in the rest of the code.
考虑使用FirstOrDefault, 代替(在此处记录),它不会在序列为空时抛出异常,而是返回可枚举类型的默认值。在这种情况下,调用的结果将是null,您应该在其余代码中检查它。
It might be cleaner still to use the AnyLinq method (documented here), which returns a bool.
这可能是清洁还是使用AnyLINQ的方法(记录在这里),它返回一个bool。
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
}
And now the obligatory one liner using the ternary operator:
现在使用三元运算符的强制性单行:
string str = "Hello1,Hello,Hello2";
string another = "Hello5";
ViewBag.test = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Any(p => p == another) ? "Match" : "No Match";
Note that I also used ==here to compare strings, which is considered more idiomatic in C#.
请注意,我==在这里也使用了比较字符串,这在 C# 中被认为更惯用。
回答by Dimitar Dimitrov
Give this a shot:
试一试:
bool hasMatch = str.Split(',').Any(x => x.Equals(another));
ViewBag.test = hasMatch ? "Match" : "No Match";

