Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to Compare 2 Brushes as you can see in the Picture. I have no Idea why its failing...

Equal Fail

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
203 views
Welcome To Ask or Share your Answers For Others

1 Answer

They won't be equal because it's doing a reference comparison and they are two different references in the heap with the same properties.

If you want to control object comparisons, you should implement the IEqualtable interface. You can then say how the objects must be compared. In this case however, since SolidColorBrush is a .NET class, we cannot implement IEquatable. There are different options

1) Use an extension method on the SolidColorBrush which compares a brush instance with another. Not a very good solution in this case though.

2) The best bet would proably be to use IEqualityComparer interface. You create a seperate class implementing IEqualityComparer, which will define how to compare 2 different objects. For instance in your example, you may want to compare the SolidColorBrush on Color and Opacity:

public class SolidColorBrushComparer : IEqualityComparer<SolidColorBrush>
{
    public bool Equals(SolidColorBrush x, SolidColorBrush y)
    {
        return x.Color == y.Color && 
            x.Opacity == y.Opacity;
    }

    public int GetHashCode(SolidColorBrush obj)
    {
        return new { C = obj.Color, O = obj.Opacity }.GetHashCode();
    }
}

And then to compare you simply do the following:

SolidColorBrush otherBrush = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FFEFEEEE"));
SolidColorBrush backgroundBrush = (SolidColorBrush)grd.Background;

if(new SolidColorBrushComparer().Equals(backgroundBrush, otherBrush))
{
   // They're equal, Yay!
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...