ObservableCollection.Contains()无法正常工作

Elm*_*lmo 5 .net c# vb.net wpf

考虑以下:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么把它添加 x = "a", y = "1"ListView

如果我ObservableCollection改为ListCollection,它也是一样的.

Gay*_*Fow 18

'Contains'方法使用Equals on对象,这只是检查内存地址是否不同.

考虑将您的班级改为此...

 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; 
     } 
}
Run Code Online (Sandbox Code Playgroud)

然后,您的循环将访问类中强类型的Equals方法,这将导致您所处的行为.

注意:字符串类ALSO继承自T的IEquatable,这允许相等运算符对字符串的内容而不是字符串的地址进行操作.