ObservableCollection.Contains()无法正常工作无法正常、工作、ObservableCollection、Contains

由网友(我在等不会等我的人i)分享简介:考虑以下几点:class Bind{public string x { get; set; }public string y { get; set; }}public partial class MainWindow : Window{public MainWindow(){InitializeCompone...

考虑以下几点:

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.

阅读全文

相关推荐

最新文章