Can't compare T value1 with T value2 = default(T). Why and how to do that on C#?

后端 未结 7 817
情话喂你
情话喂你 2020-12-19 05:53

I\'m trying the following:

T value1 = el.value; // it\'s of type T already
T value2 = default(T);
if (value1 != value2) // gives the following error: Operato         


        
相关标签:
7条回答
  • 2020-12-19 06:15

    if you use value1.equals(value2) then you have a problem with null values. Better:
    object.equals(value1,value2)

    Or for reference types (be careful):
    object.referenceEquals(value1,value2)

    0 讨论(0)
  • 2020-12-19 06:15

    Another thing that you could do is define the comparison operator (actually, the difference operator here) to be able to compare elements of the type T. By itself, the compiler cannot really know what you mean when you write value1 != value2, except if the operator has been defined previously.

    To define an operator, you'd use

    public operator!=(T a, T b) {
        // Comparison code; returns true or false
    }
    
    0 讨论(0)
  • 2020-12-19 06:20

    You can either use a constraint of where T : IEquatable<T> as Henk mentioned, or ignore constraints and use:

    if (!EqualityComparer<T>.Default.Equals(value1, value2))
    
    0 讨论(0)
  • 2020-12-19 06:21

    What's wrong with this?

    if (!value1.Equals(value2))
    

    Should be "cross object".. :)

    0 讨论(0)
  • 2020-12-19 06:24

    Not all types have a default implementation of the == operator. For classes, the default == operation is to compare the references. For structs, no such default implementation exists.

    You can add type constraints to generic type parameters in C#. Unfortunately, you can't define a constraint that forces the type to have an implementation of the == operator. The best you can do is to force the type to be a class: where T: class. An article about type parameter constraints in C#

    0 讨论(0)
  • 2020-12-19 06:28

    try

    Equals(value1, value2)
    

    A good way of avoiding null ref's

    0 讨论(0)
提交回复
热议问题