Equality of two structs in C#

前端 未结 6 855
独厮守ぢ
独厮守ぢ 2020-12-17 21:15

I look for an equality between two instances of this struct.

public struct Serie
{
    T[]         X; 
    double[]    Y;

    public Serie(T[] x, d         


        
6条回答
  •  星月不相逢
    2020-12-17 21:46

    Calling == performs reference equality on arrays - they don't compare the contents of their elements. This basically means that a1 == a2 will only return true if the exact same instance - which isn't what you want, I think..

    You need to modify your operator == to compere the contents of the x array, not it's reference value.

    If you're using .NET 3.5 (with link) you can do:

    public static bool operator ==(Serie s1, Serie s2)
    {
        return ((s1.X == null && s2.X == null) || s1.X.SequenceEquals( s2.X )) 
               && s1.Y == s2.Y;
    }
    

    If you need to do deep comparison (beyond references), you can supply SequenceEquals with a custom IEqualityComparer for the type of T.

    You probably should also consider implementing the IEquatable interface for your struct. It will help your code work better with LINQ and other parts of the .NET framework that perform object comparisons.

提交回复
热议问题