【问题标题】:Strange, IEnumerable.ToList() creates entirely new objects奇怪的是,IEnumerable.ToList() 创建了全新的对象
【发布时间】:2013-08-26 03:05:49
【问题描述】:

我知道 IEnumerable.ToList() 应该创建一个新列表,但项目指向 IEnumerable 中的相同原始项目,如 ToList()-- Does it Create a New List? 中所述

但是,我在使用 VS 2012 的代码中出现了一些奇怪的行为; WPF;和 .NET 4.0。当 IEnumerable.SequenceEquals() 似乎没有按我预期的那样工作时,它就开始了。我仔细研究了我的 QuickWatch 对话框,令人难以置信的是,以下语句的计算结果为 false:

this.Items.First () == this.Items.ToList ()[ 0 ]

我什至尝试过:

this.Items.ToList ().IndexOf(this.Items.First ())

评估为 -1。

Items 被声明为 WPF 自定义控件上的属性,如下所示:

public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register (
        "Items", 
        typeof ( IEnumerable<UserLayoutType> ), 
        typeof ( UserLayoutSelectorControl ),
        new FrameworkPropertyMetadata ( null, FrameworkPropertyMetadataOptions.AffectsRender, UserLayoutSelectorControl.PropertyChanged ) );


public IEnumerable<UserLayoutType> Items
{
    get
    {
        return ( IEnumerable<UserLayoutType> ) this.GetValue ( UserLayoutSelectorControl.ItemsProperty );
    }
    set
    {    
        this.SetValue ( UserLayoutSelectorControl.ItemsProperty, value );                
    }
}

UserLayoutType 只是 XSD 工具生成的一个类,声明如下:

// 
// This source code was auto-generated by xsd, Version=4.0.30319.17929.
// 
namespace MyAssays.UserLayoutCore.UserLayoutUtility {
    using System.Xml.Serialization;


    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlRootAttribute("UserLayout", Namespace="", IsNullable=false)]
    public partial class UserLayoutType {

这是工厂类中首先创建 UserLayoutType 项的方法:

public static IEnumerable<UserLayoutType> CreateFromFolder ( string folderPath )
    {
        if (String.IsNullOrEmpty(folderPath))
            throw new ArgumentNullException("folderPath", "Folder path must not be null");

        var userLayoutXmlFilePaths = Directory.GetFiles ( folderPath ).Where ( filePath => filePath.EndsWith ( ".UserLayout.xml", StringComparison.InvariantCultureIgnoreCase ) );
        return userLayoutXmlFilePaths.Select(filePath => UserLayoutFactory.CreateFromFile(filePath));
    }

    public static UserLayoutType CreateFromFile ( string filePath )
    {
        using ( var stream = new StreamReader ( filePath ) )
        {
            return ( UserLayoutType ) new XmlSerializer ( typeof ( UserLayoutType ) ).Deserialize ( stream );
        }
    }

有人知道发生了什么吗?见下图:

【问题讨论】:

  • 嗨,请尝试 .Equals 方法,即。 this.Items.First().equals(this.Items.ToList ()[ 0 ])
  • 声明的物品是什么?我认为最好尝试创建一小段简单的代码来显示您正在谈论的问题。然后在您的问题中发布代码。除此之外,您还需要了解 == 和 .Equals() 之间的区别
  • UserLayoutType 有没有可能是一个结构体?
  • 可能是您的Items 属性在每次调用时都会创建新对象。下面的评价是什么? var left = this.Items.First(); var right = this.Items.First(); var result = left == right;
  • 因此,当我使用 List 而不是真正的 IEnumerable 作为属性的初始值时,一切正常。这表明一些重要的事情;因此,需要更新 (stackoverflow.com/questions/2774099/…) 上问题的答案。如果 IEnumerable 是真正的 IEnumerable(即不仅仅是一个封装为可枚举的集合),ToList() 可能不会返回与 IEnumerable 中相同的对象引用。它将返回一个新的对象列表,这些对象可能与 IEnumerable 再次枚举时产生的对象不同甚至不相等

标签: c# list .net-4.0 ienumerable


【解决方案1】:

导致您从中看到新对象的主要原因可能是 IEnumerable&lt;T&gt; 包装了一个生成器,而不是一个物化集合。

这里有一个简单的LINQPad 程序来演示:

void Main()
{
    IEnumerable<string> collection =
        from index in Enumerable.Range(1, 10)
        select "Index=" + index;

    var list1 = collection.ToList();
    var list2 = collection.ToList();

    ReferenceEquals(list1[0], list2[0]).Dump();
}

这将打印False

它会这样做是因为枚举集合的行为(在本例中为.ToList())将执行延迟的 LINQ 查询,并且由于我们枚举集合两次,我们执行它两次,产生不同的实例相同的值。

【讨论】:

    猜你喜欢
    • 2023-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    相关资源
    最近更新 更多