为什么此代码引发InvalidOperationException? [英] Why is this code throwing an InvalidOperationException?

查看:156
本文介绍了为什么此代码引发InvalidOperationException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我的代码应使 ViewBag.test 属性等于不匹配 ,但是会引发 InvalidOperationException

I think that my code should make the ViewBag.test property equal to "No Match", but instead it throws an 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
}


推荐答案

如您所见,此处第一个方法将引发 InvalidOperationException 。由于拆分结果的任何元素都不等于 Hello5 ,因此结果为空列表。在该列表上使用 First 会引发异常。

As you can see here, the First method throws an InvalidOperationException when 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 First on that list will throw the exception.

请考虑使用 FirstOrDefault ,而不是(在此处记录),而不是在sequence为空,返回可枚举类型的默认值。在这种情况下,调用的结果将为 null ,您应该在其余代码中进行检查。

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.

仍然可以使用任何 Linq方法(记录在此处),它会返回 bool

It might be cleaner still to use the Any Linq method (documented here), which returns a 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
}

现在必须使用三元运算符

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

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

Note that I also used == here to compare strings, which is considered more idiomatic in C#.

这篇关于为什么此代码引发InvalidOperationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆