Operator '??' cannot be applied to operands of type 'T' and 'T'

前端 未结 8 714
旧巷少年郎
旧巷少年郎 2021-02-06 20:34

I have the following generic method, but VS gives me a compile error on that. (Operator \'??\' cannot be applied to operands of type \'T\' and \'T\')

public stat         


        
相关标签:
8条回答
  • 2021-02-06 21:20

    You need to specify that your T type is a class with a constraint on the generic type:

    public static T Method<T>(T model) where T : class, new()
    {
        return model ?? new T();
    }
    
    0 讨论(0)
  • 2021-02-06 21:22

    Since T can be any type, there is no guarantee that T will have a static ?? operator or that the type T is nullable.

    ?? Operator (C# Reference)

    The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types.

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