我明白,我正在嘗試做的是一些破解,但它仍然很有趣。非例外情況下,數組越界
我處於很有可能數組可能沒有我期望的項目數量的情況。
這裏的概念:
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]是否爲空,因爲它不存在。 –