ObservableCollection.Contains() Doesn't Work Correctly

前端 未结 4 1331
时光说笑
时光说笑 2021-01-13 00:55

Consider the following:

class Bind
{
    public string x { get; set; }
    public string y { get; set; }
}
public partial class MainWindow : Window
{
    pub         


        
相关标签:
4条回答
  • 2021-01-13 01:20

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

    Consider changing your class to this...

     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; 
         } 
    }
    

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

    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.

    0 讨论(0)
  • 2021-01-13 01:38

    You should inform about comparer:

    "Elements are compared to the specified value by using the default equality comparer, Default."

    In EqualityComparer.Default Property you can see an example.

    0 讨论(0)
  • 2021-01-13 01:42

    Because "a" != "a". At least, not always.

    Contains() will check memory addresses, not the actual contents. You cannot insert the same object twice, and "a" isn't the same object as "a" (at least, not here).

    0 讨论(0)
  • 2021-01-13 01:44

    Because that you have added that value set to CX:

    cX.Add(new Bind { x = "a", y = "1" });
    

    and to CY:

    cY.Add(new Bind { x = "a", y = "1" });
    

    And those are different objects.

    If you want to see if a given key is present, you will need to change to a dictionary or use Linq.

    0 讨论(0)
提交回复
热议问题