我明白,我正在尝试做的是一些破解,但它仍然很有趣。非例外情况下,数组越界
我处于很有可能数组可能没有我期望的项目数量的情况。
这里的概念:
namespace TESTAPP
{
class Program
{
static void Main(string[] args)
{
string derp = "foooooo";
//The split is important, you might not have the character there to split by
Writer(derp.Split('x')[0] ?? ".");
Writer(derp.Split('x')[1] ?? ".");
}
private static void Writer(string writeme)
{
Console.WriteLine(writeme ?? "..");
}
}
}
当然,我执行上述打印时不是太惊讶:
foooooo
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at TESTAPP.Program.Main(String[] args) in [snip]\TESTAPP\Program.cs:line 15
我应该如何处理这种情况在逻辑上? A try/catch
块似乎矫枉过正。
你如何处理它?你需要抛出异常,还是可以从中恢复?如果没有足够的字符串,对您的程序意味着什么? –
'derp.Split('x')[1] ?? “。”表示如果'derp.Split('x')[1]'中没有任何内容会打印字符'“。”'“。 – Izzy
你应该得到一个最难读的代码的奖励;)问题出现在'derp.Split('x')[1]'中。你不能检查[1]是否为空,因为它不存在。 –