Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

c# - How to Compare SolidColorBrushes?

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...