我知道我正在尝试做的有点像 hack,但它仍然很有趣。
我处于一种情况,一个数组很可能没有我期望的那么多项目。
这是概念:
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
我应该如何从逻辑上处理这种情况?一个try/catch
块似乎过大了。