What should I do about “Possible compare of value type with 'null'”?

前端 未结 4 1230
自闭症患者
自闭症患者 2021-02-04 23:06

While writing this method for a custom NUnit Constraint.

    private void AddMatchFailure(string failureName, TExpected expected, TActu         


        
4条回答
  •  清酒与你
    2021-02-04 23:31

    What are the rules when comparing a ValueType to null and how should I write the method to account for that without limiting the generic parameters by adding a class constraint?

    If you do not know that they will be reference types, then you can say

    private void AddMatchFailure(
        string failureName,
        TExpected expected,
        TActual actual
    ) {
        _matchFailures.Add(
            String.Format(MatchFailureFormat, failureName,
            IsDefault(expected) ? DefaultStringForType() : expected.ToString(),
            IsDefault(actual) ? DefaultStringForType() : actual.ToString()
        );
    }
    
    private bool IsDefault(T value) {
        if(typeof(T).IsValueType) {
            return default(T).Equals(value);
        }
        else {
            return Object.Equals(null, value);
        }
    }
    
    private string DefaultStringForType() {
        if(typeof(T).IsValueType) {
            return default(T).ToString();
        }
        else {
            return "null";
        }
    }
    

提交回复
热议问题