Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何转换列表<;字符串>;只读集合<;字符串>;在C中#_C#_.net_String_Collections - Fatal编程技术网

C# 如何转换列表<;字符串>;只读集合<;字符串>;在C中#

C# 如何转换列表<;字符串>;只读集合<;字符串>;在C中#,c#,.net,string,collections,C#,.net,String,Collections,我想将输入到字符串列表的项目转换为: System.Collections.ObjectModel.ReadOnlyCollection<string> System.Collections.ObjectModel.ReadOnlyCollection 我试过使用: (System.Collections.ObjectModel.ReadOnlyCollection<string>)listname (System.Collections.ObjectModel.R

我想将输入到字符串列表的项目转换为:

System.Collections.ObjectModel.ReadOnlyCollection<string>
System.Collections.ObjectModel.ReadOnlyCollection
我试过使用:

(System.Collections.ObjectModel.ReadOnlyCollection<string>)listname
(System.Collections.ObjectModel.ReadOnlyCollection)列表名

但是它返回一个错误。

ReadOnlyCollection的构造函数接受IList

这里有一些参考资料

var myreadonlycollection=new ReadOnlyCollection(listname);
var readonlyCollection=新的readonlyCollection(列表);

您可以使用构造函数中的现有列表创建新实例

var readOnlyList = new ReadOnlyCollection<string>(existingList);
var readOnlyList=new ReadOnlyCollection(existingList);
如果您有:

List name=newlist(){“Rod”、“Jane”、“Freddy”}

然后你可以说:

ReadOnlyCollection readOnlyNames=names.AsReadOnly()


这不会复制列表。相反,readonly集合存储对原始列表的引用,并禁止对其进行更改。但是,如果您通过
names
修改基础列表,那么
readOnlyNames
也会更改,因此如果可以,最好放弃可写实例。

其他答案是正确的,因为您需要将
IList
传递给
ReadOnlyCollection
的构造函数

我发现在
IEnumerable
上有一个扩展方法非常有用,它有助于创建
ReadOnlyCollection

publicstatic ReadOnlyCollection到adonlycollection(
这是(不可数的来源)
{
如果(source==null)抛出新的ArgumentNullException(“source”);
返回新的只读集合(
源代码为IList??source.ToList());
}

@Errorstacks。。。谢谢你的否决票。但是你不应该剽窃。@Errorstacks….哈哈,真有趣,我从来没说过你在抄袭我。但是你从MSDN复制了准确的代码。只需参考链接并进行描述。因此,您的
源代码.ToReadOnlyCollection()
与内置的
源代码.ToList().AsReadOnly()
相当。(此外,根据传入的
IEnumerable
是否已经是
IList
,代码的行为也会有所不同。如果已经是,则该源集合未来的任何变化都将反映在
ReadOnlyCollection
中;如果不是,则
ReadOnlyCollection
实际上是不可变的。)这正是我想要的。谢谢大家回答这个问题。可能的副本
var readonlyCollection = new ReadOnlyCollection<string>(list);
var readOnlyList = new ReadOnlyCollection<string>(existingList);
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());
}