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

后端 未结 7 832
情话喂你
情话喂你 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:20

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

    if (!EqualityComparer.Default.Equals(value1, value2))
    

提交回复
热议问题