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

前端 未结 8 729
旧巷少年郎
旧巷少年郎 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:19

    Many have pointed out already that adding the class constraint for the generic will solve the problem.

    If you want your method to be applicable to Nullable too, you can add an overload for it:

    // For reference types
    public static T Method(T model) where T : class, new()
    {
        return model ?? new T();
    }
    
    // For Nullable
    public static T Method(T? model) where T : struct
    {
        return model ?? new T(); // OR
        return model ?? default(T);
    }
    

提交回复
热议问题