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!
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…