C# 避免出現數組越界錯誤

需要對長度進行判斷,如果下標越界,會出錯:

List<string> test = new List<string>();
test.Add("beijing");
test.Add("shanghai");
test.Add(null);
test.Add("quzhou");

if (test.Count() >= 4)
{
    string a = test[2] == null ? "" : "hello";
    string b = test[3] == null ? "" : "world";

    Console.WriteLine("a,b:{0} {1}", a, b);
}

結果:

------------------------------------------------------------------------------------

新方法,如果下標越界,可以填充默認值,不會出錯:

List<string> test = new List<string>();
test.Add("beijing");
test.Add("shanghai");
test.Add(null);
test.Add("quzhou");

//if (test.Count() >= 4)
//{
//    string a = test[2] == null ? "" : "hello";
//    string b = test[3] == null ? "" : "world";

//    Console.WriteLine("a,b:{0} {1}", a, b);
//}

string a = test.ElementAtOrDefault(3) ?? "hello";
string b = test.ElementAtOrDefault(4) ?? "world";

Console.WriteLine("a,b:{0} {1}", a, b);

 

結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章