2 回答

TA貢獻1806條經驗 獲得超8個贊
這些是可能的方法:
//APPROACH 1
List<int> items = GetIntegerStuff();
if (items == null)
{
items = new List<int>();
}
//APPROACH 2
List<int> items = GetIntegerStuff() ?? new List<int>();
//APPROACH 3
List<int> items = GetIntegerStuff();
items = items ?? new List<int>();
//APPROACH 4
List<int> items = GetIntegerStuff();
items = items == null ? new List<int>() : items;
我會選擇2號,從我的角度來看,它是最干凈的。
為了完整起見,在某些情況下您可以找到類似的內容:
class Program
{
private static List<int> _items = new List<int>();
private static List<int> Items
{
get
{
return _items;
}
set
{
_items = value ?? new List<int>();
}
}
static void Main(string[] args)
{
//APPROACH 5
Items = GetIntegerStuff();
}
private static Random Random = new Random();
private static List<int> GetIntegerStuff()
{
switch (Random.Next(0, 2))
{
case 0:
return null;
break;
default:
return new List<int>();
break;
}
}
}
這對性能有害嗎?
List<int> items = GetIntegerStuff();
items = items ?? new List<int>();
不,但它實際上會執行更多關于以下方面的指令:
List<int> items = GetIntegerStuff();
if (items == null)
{
items = new List<int>();
}
或者
List<int> items = GetIntegerStuff() ?? new List<int>();
- 2 回答
- 0 關注
- 203 瀏覽
添加回答
舉報