Operator overloading and different types

前端 未结 5 1527
轮回少年
轮回少年 2021-01-04 09:33

I have a class Score which is going to be heavily used in comparisons against integers. I was planning on overloading the == operator to enable these comparisons as per th

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-04 10:16

    I might go ahead and define an implicit conversion from int to Score, so that when you deal with equality, you only need to deal with a single type.

    public static implicit operator Score(int value)
    {
        return new Score { Value = value }; // or new Score(value);
    }
    // define bool operator ==(Score score1, Score score2)
    
    // elsewhere 
    Score score = new Score { Value = 1 };
    bool isScoreOne = (score == 1);
    

    And while you're defining your own == operator, do remember to go ahead and define !=, and override Equals and GetHashCode.

提交回复
热议问题