【问题标题】:Why is this code throwing an InvalidOperationException?为什么这段代码会抛出 InvalidOperationException?
【发布时间】:2013-05-19 15:36:46
【问题描述】:

我认为我的代码应该使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
}

【问题讨论】:

  • @SLaks 代码返回 System.InvalidOperationException 而不是在页面上显示“No Match”。
  • 它不会返回 InvalidOperationException,它会抛出它。主要是因为该列表中没有字符串等于“Hello5”。你想完成什么?
  • .First() 抛出它,如果没有匹配,请尝试 FirstOrDefault() 并检查 null

标签: c# asp.net-mvc exception equality invalidoperationexception


【解决方案1】:

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

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

使用Any Linq 方法(记录在here)可能更简洁,它返回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
}

现在必须使用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# 中被认为更惯用。

【讨论】:

  • 对此表示赞成,但代码不清楚我完全不知道他想做什么。
  • 当变量 str 在逗号和“不匹配”之间包含变量 another 时,我解释了这个问题,他或她试图将 ViewBag.test 设置为“匹配”否则。这就是你的意思吗,@user2398766?
  • 我同意这一点,但我不能说!
【解决方案2】:

试一试:

bool hasMatch = str.Split(',').Any(x => x.Equals(another));

ViewBag.test = hasMatch ? "Match" : "No Match";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多