ObservableCollection.Contains()无法正常工作 [英] ObservableCollection.Contains() Doesn't Work Correctly

查看:224
本文介绍了ObservableCollection.Contains()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下几点:

class Bind
{
    public string x { get; set; }
    public string y { get; set; }
}
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        ObservableCollection<Bind> cX = new ObservableCollection<Bind>();
        ObservableCollection<Bind> cY = new ObservableCollection<Bind>();
        cX.Add(new Bind { x = "a", y = "1" });
        cX.Add(new Bind { x = "b", y = "2" });
        cY.Add(new Bind { x = "a", y = "1" });
        foreach (var i in cX)
        {
            if (!cY.Contains(i)) { lv.Items.Add(i); } //lv is a ListView control
        }
    }
}

为什么把它添加 X =A,Y =1的ListView

如果我修改的ObservableCollection 列表集合 ,它确实是相同的。

If I change ObservableCollection to List or Collection, it does the same.

推荐答案

在'包含'方法使用的Equals对象,而这只是检查该内存地址是不同的。

The 'Contains' method uses the Equals on object, and this simply checks that the memory addresses are different.

考虑更改类本...

 class Bind : IEquatable<Bind> {
     public string x { get; set; }
     public string y { get; set; }
     public bool Equals(Bind other)
     {
         return x == other.x && y == other.y; 
     } 
}

那么

您回路将访问在你的类的强类型的equals方法,而这将导致你以后的行为。

Your loop will then visit the strongly typed Equals method in your class, and this will result in the behaviour you are after.

注:串类也继承的T IEquatable,这是什么让平等运算符对字符串的内容进行操作,而不是字符串的地址

NOTE: the string class ALSO inherits from IEquatable of T and that is what allows the equality operator to operate on the content of the string rather than the address of the string.

这篇关于ObservableCollection.Contains()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆