人们试图帮助你,而你却不听。
你是如何“创造”一个?
IEnumerable<T>
Can not new an IEnumerable
此语法失败
IEnumerable<Person> IPeople = new IEnumerable<Person>();
您可能正在应用程序加载中创建对 IEnumerable 的引用。
但是你没有创建一个 IEnumerable 对象,因为没有这样的东西。
IEnumerable 是一个接口而不是一个集合 - 它不能被更新。
请参阅下面的代码。
在 16 毫秒内从 IEnumerable ctor 创建了一个 100,000 的 ObservableCollection。
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
System.Diagnostics.Debug.WriteLine(iPeople.Count().ToString());
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString()); // 13 ms
sw.Restart();
ObservableCollection<Person> ocPeople = new ObservableCollection<Person>(iPeople);
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString()); // 16 ms
sw.Restart();
System.Diagnostics.Debug.WriteLine(iPeople.Count().ToString());
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString()); // 8 ms
sw.Restart();
System.Diagnostics.Debug.WriteLine(ocPeople.Count().ToString());
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString()); // 1 ms
sw.Restart();
List<Person> lPeople = new List<Person>(iPeople);
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString()); // 10 ms
sw.Restart();
ObservableCollection<Person> ocPeople2new = new ObservableCollection<Person>(lPeople);
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString()); // 6 ms
public IEnumerable<Person> iPeople
{
get
{
for (int i = 0; i < 100000; i++) yield return new Person(i);
}
}
public class Person
{
public Int32 ID { get; private set; }
public Person(Int32 id) { ID = id; }
}