Can't operator == be applied to generic types in C#?

前端 未结 12 937
囚心锁ツ
囚心锁ツ 2020-11-22 02:21

According to the documentation of the == operator in MSDN,

For predefined value types, the equality operator (==) returns true if th

12条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-22 02:47

    Well in my case I wanted to unit-test the equality operator. I needed call the code under the equality operators without explicitly setting the generic type. Advises for EqualityComparer were not helpful as EqualityComparer called Equals method but not the equality operator.

    Here is how I've got this working with generic types by building a LINQ. It calls the right code for == and != operators:

    /// 
    /// Gets the result of "a == b"
    /// 
    public bool GetEqualityOperatorResult(T a, T b)
    {
        // declare the parameters
        var paramA = Expression.Parameter(typeof(T), nameof(a));
        var paramB = Expression.Parameter(typeof(T), nameof(b));
        // get equality expression for the parameters
        var body = Expression.Equal(paramA, paramB);
        // compile it
        var invokeEqualityOperator = Expression.Lambda>(body, paramA, paramB).Compile();
        // call it
        return invokeEqualityOperator(a, b);
    }
    
    /// 
    /// Gets the result of "a =! b"
    /// 
    public bool GetInequalityOperatorResult(T a, T b)
    {
        // declare the parameters
        var paramA = Expression.Parameter(typeof(T), nameof(a));
        var paramB = Expression.Parameter(typeof(T), nameof(b));
        // get equality expression for the parameters
        var body = Expression.NotEqual(paramA, paramB);
        // compile it
        var invokeInequalityOperator = Expression.Lambda>(body, paramA, paramB).Compile();
        // call it
        return invokeInequalityOperator(a, b);
    }
    

提交回复
热议问题