gpt4 book ai didi

c# - 如何在 C# 中将 IList 转换为 List,性能良好且简洁?

转载 作者:行者123 更新时间:2023-12-02 17:41:02 25 4
gpt4 key购买 nike

尽管这些问题的答案中有一些信息:Cast IList to ListPerformance impact when calling ToList()他们没有回答我的具体问题。我有一个类是列表的包装器。此类设计为通过 WCF 服务发送并实现一些附加功能。

[DataContract]
public class DataContractList<T> : IList<T>
{
[DataMember]
protected readonly List<T> InnerList;

public DataContractList()
{
InnerList = new List<T>();
}

public DataContractList(IList<T> items)
{
InnerList = items as List<T> ?? items.ToList(); //Question is about this line.
}
}

因此有一个接受 IList<T> 的构造函数接口(interface)(为了鼓励接口(interface)编程)。我需要转换这个IList<T>接口(interface)List<T>类(class)。我可以使用.ToList()扩展方法,在内部创建 List<T> 的新实例通过将 IEnumrable“this”参数传递给它的构造函数(参见 here )。通用List<T>构造函数只是迭代这个可数。因此,如果没有必要,我想阻止此迭代(如果内部项目参数已经是 List<T> )。那么,这是执行此操作的最佳方式(就性能和可读性而言):InnerList = items as List<T> ?? items.ToList(); ?如果不是,请提供更好的方法和原因的详细信息。

最佳答案

尽量避免迭代列表是一个好主意,但还有更多需要考虑。

您已保护 InnerList 属性不被公共(public)访问,如果您只是将列表分配给该属性,那么这种努力是毫无意义的。如果我将一个列表发送到构造函数中并保留对该列表的引用,那么我就拥有对该类内部使用的列表的引用:

List<sting> list = new List<string>();
var dc = new DataContractList(list);

// now I can manipulate the internal list:
list.Add("Woaaah! Where did that come from?");

为了保持内部列表内部,即使输入是列表,您也始终会创建一个新列表:

public DataContractList(IList<T> items)
{
InnerList = new List<T>(items);
}

关于c# - 如何在 C# 中将 IList<T> 转换为 List<T>,性能良好且简洁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32896912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com