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

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

    For some reason the ?? operator can't be used on non-nullable types, even though it is supposed to be equivalent to model == null ? new T() : model, and you are allowed a null comparison with a non-nullable type.

    You can get exactly what you're looking for without any additional constraints by using the ternary operator instead, or an if statement:

    public static T Method(T model) where T : new()
    {
       var m = model == null ? new T() : model;
    }
    

提交回复
热议问题