在下面的代码中,该Select()方法是否足够智能,以便在内部保持列表的大小,以使ToArray()方法便宜?
List<Thing> bigList = someBigList;
var bigArray = bigList.Select(t => t.SomeField).ToArray();
Run Code Online (Sandbox Code Playgroud)
这很容易检查,而无需查看实现.只需创建一个实现的类IList<T>,并在Count属性中添加跟踪:
class MyList<T> : IList<T>
{
private readonly IList<T> _list = new List<T>();
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}
public void Add(T item)
{
_list.Add(item);
}
public void Clear()
{
_list.Clear();
}
public bool Contains(T item)
{
return _list.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
return _list.Remove(item);
}
public int Count
{
get
{
Console.WriteLine ("Count accessed");
return _list.Count;
}
}
public bool IsReadOnly
{
get { return _list.IsReadOnly; }
}
public int IndexOf(T item)
{
return _list.IndexOf(item);
}
public void Insert(int index, T item)
{
_list.Insert(index, item);
}
public void RemoveAt(int index)
{
_list.RemoveAt(index);
}
public T this[int index]
{
get { return _list[index]; }
set { _list[index] = value; }
}
#region Implementation of IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
如果Count访问该属性,则此代码应打印"Count visited":
var list = new MyList<int> { 1, 2, 3 };
var array = list.Select(x => x).ToArray();
Run Code Online (Sandbox Code Playgroud)
但它不会打印任何东西,所以不,它不会记录计数.当然可能有一个特定的优化List<T>,但似乎不太可能......
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |