【发布时间】:2016-04-24 23:36:44
【问题描述】:
我正在做一个项目,我注意到该人使用列表来表示一段代码。如果是我,我会出于个人喜好而使用数组,因为这是我所知道的。看看下面的代码,选择列表对数组有什么好处?
List<string> errors = new List<string>();
if (ddDirector.SelectedItem.Value == "")
errors.Add("You must select an item in the Director list.");
if (errors.Count > 0)
{
ErrorList.InnerHtml = "Please correct the following issues below:<br/><ul>";
foreach (string e in errors)
{
ErrorList.InnerHtml += String.Format("<li>{0}</li>", e);
}
ErrorList.InnerHtml += "</ul>";
}
return (errors.Count()==0);
【问题讨论】:
-
A List 具有在给定位置或从开头或结尾轻松添加和减去元素的方法以及许多其他方法。 msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx
-
老实说,根据我的经验,人们使用
List<T>是因为他们很懒且易于使用。但从性能角度来看,它并不总是最佳选择。 -
如果您不确定项目的数量,请查看列表。
-
@CodingGorilla 公平地说,你用“根据我的经验”来限定它,但我仍然觉得这是一个粗略的概括。
-
Eric Lippert 的分析也很有用:blogs.msdn.microsoft.com/ericlippert/2008/09/22/…