简体   繁体   中英

C# Enums and Generics

Why does the compiler reject this code with the following error? (I am using VS 2017 with C# 7.3 enabled.)

CS0019 Operator '==' cannot be applied to operands of type 'T' and 'T'

public class GenericTest<T> where T : Enum
{
    public bool Compare(T a, T b)
    {
        return a == b;
    }
}

The version without generics is of course perfectly valid.

public enum A { ONE, TWO, THREE };

public class Test
{
    public bool Compare(A a, A b)
    {
        return a == b;
    }
}

The compiler cannot rely on the operator == being implemented for every type provided for T . You could add a constraint to restrict T to class , but that would not allow you to use it for your enum, due to the enum not being a reference type. Adding struct as a constraint would also not allow you to use the operator because structs don't always have an implementation of the == operator, but you could use a.Equals(b) in that case instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM