.NET v2
当 List 有一个非常有用的(4 me)方法 AsReadOnly() 时,LinkedList 没有这样的方法。
有没有办法“快速”连接内部LinkedList以仅从外部代码中读取?
为什么不只返回一个IEnumerable<T>
?如果您只想让用户枚举列表而不修改它*,IEnumerable 是显而易见的选择。
如果你想拥有 LinkedList 接口的只读接口,你可以包装 LinkedList,将只读方法转发到被包装的列表并拒绝任何更改。
*) 请记住,ReadOnlyCollection 和 IEnumerable 都不会阻止调用者在引用类型集合的情况下更改对象的状态。如果对象也应该是只读的,则需要将其作为其类型的一部分来实现。
ReadOnlyCollection<T>
将IList<T>
as 参数传递给构造函数。LinkedList<T>
没有实现这个接口。List<T>
有一个构造函数重载,它接受一个IEnumerable<T>
as 参数,并LinkedList<T>
实现了这个接口。所以以下应该工作:
LinkedList<int> linked = new LinkedList<int>();
// populate the list
ReadOnlyCollection<int> readOnly = new ReadOnlyCollection<int>(
new List<int>(linked));
它使用 的实例List<T>
将项目携带到ReadOnlyCollection<T>
构造函数中。
class FixedLinkedList<T> : LinkedList<T>, IList<T>
{
public T this[int index]
{
get
{
return GetAt(index).Value;
}
set
{
GetAt(index).Value = value;
}
}
public int IndexOf(T item)
{
int i = 0;
var node = First;
while (node!= null && !node.Value.Equals(item))
{
i++;
node = node.Next;
}
if (node == null)
{
return -1;
}
return i;
}
public void Insert(int index, T item)
{
AddBefore(GetAt(index), new LinkedListNode<T>(item));
}
public void RemoveAt(int index)
{
Remove(GetAt(index));
}
private LinkedListNode<T> GetAt(int index)
{
CheckIndex(index);
int i = 0;
var node = First;
while (i < index)
{
i++;
node = node.Next;
}
return node;
}
private void CheckIndex(int index)
{
if (index < 0)
{
throw new ArgumentOutOfRangeException(
nameof(index),
"Parameter must be greater or equal to 0.");
}
if (index >= Count)
{
throw new ArgumentOutOfRangeException(
nameof(index),
"Parameter must be lower than the list item Count.");
}
}
}
LinkedList<T>
简而言之没有实现IList
,没有没有办法快速做到这一点。如果您将 LinkedList 转换为 List,您可能会失去所需的功能。
LinkedList<T>
没有为您提供任何子类化功能,因此您需要自己编写。我想下一个请求是“你能告诉我怎么做吗”