Equality comparison between multiple variables

前端 未结 14 1282
梦毁少年i
梦毁少年i 2020-11-29 08:00

I\'ve a situation where I need to check whether multiple variables are having same data such as

var x=1;
var y=1;
var z=1;

I want to check

14条回答
  •  一整个雨季
    2020-11-29 08:42

    if (x == y && y == z && z == 1)
    

    is the best you can do, because

    y == z evaluates to a boolean and you can't compare x with the result:

    x == (y == z)
    
    |    |
    
    int  bool
    

    I would do this:

    public bool AllEqual(params T[] values) {
        if(values == null || values.Length == 0)
             return true;
        return values.All(v => v.Equals(values[0]));    
    }
    
    // ...
    
    if(AllEqual(x, y, z)) { ... }
    

提交回复
热议问题