我想将输入的项目转换为字符串列表:
System.Collections.ObjectModel.ReadOnlyCollection<string>
我尝试了以下方法:
(System.Collections.ObjectModel.ReadOnlyCollection<string>)listname
但它返回了一个错误。
我想将输入的项目转换为字符串列表:
System.Collections.ObjectModel.ReadOnlyCollection<string>
我尝试了以下方法:
(System.Collections.ObjectModel.ReadOnlyCollection<string>)listname
但它返回了一个错误。
您可以在构造函数中使用现有的 List 来创建新实例。
var readOnlyList = new ReadOnlyCollection<string>(existingList);
List<string> names=new List<string>(){"Rod", "Jane", "Freddy"};
那么你可以使用如下代码:
ReadOnlyCollection<string> readOnlyNames=names.AsReadOnly();
该操作并不会复制列表,而是创建一个只读集合来存储原始列表的引用,并且禁止修改它。但是,如果您通过names
修改了基础列表,那么readOnlyNames
也将发生变化,因此最好在能够的情况下放弃可写实例。ReadOnlyCollection的构造函数接受一个IList。
这里有一些参考资料http://msdn.microsoft.com/en-us/library/ms132476.aspx
var myreadonlycollection = new ReadOnlyCollection<string>(listname);
var readonlyCollection = new ReadOnlyCollection<string>(list);
IList<T>
传递给ReadOnlyCollection<T>
的构造函数。IEnumerable<T>
上有一个扩展方法,可以方便地创建ReadOnlyCollection<T>
:public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(
this IEnumerable<T> source)
{
if (source == null) throw new ArgumentNullException("source");
return new ReadOnlyCollection<T>(
source as IList<T> ?? source.ToList());
}
source.ToReadOnlyCollection()
等同于内置的 source.ToList().AsReadOnly()
。另外,你的代码根据传入的 IEnumerable<>
是否已经是 IList<>
行为不同。如果是 IList<>
,那么源可变集合的任何将来更改都会反映在你的 ReadOnlyCollection<>
中;否则,你的 ReadOnlyCollection<>
就相当于不可变的。 - LukeH