【问题标题】:A value of type '<null>' cannot be used as a default parameter because there are no standard conversions to type 'T''<null>' 类型的值不能用作默认参数,因为没有标准转换为 'T' 类型
【发布时间】:2015-12-20 08:03:48
【问题描述】:

我收到错误:

'' 类型的值不能用作默认参数,因为没有标准转换为 'T' 类型

在尝试编写这段代码时

protected T GetValue<T>(Expression<Func<T>> property, T defaultValueIfNull = null);

有没有人知道如何制作空值类型。有没有办法做到这一点?

【问题讨论】:

  • protected T GetValue&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; property, T defaultValueIfNull = null) where T:class

标签: c# generics type-conversion nullable


【解决方案1】:

T 类型没有限制,所以它可以是值类型。
您可以将方法定义重写为

protected T GetValue<T>(Expression<Func<T>> property, T defaultValueIfNull = default(T));


这意味着 null 对于引用类型和值类型的默认值。

【讨论】:

  • 实际上,如果你不打算将值类型传递给这个方法,最好在方法上添加约束或(如果类型 T 由类定义)在类上。
【解决方案2】:

T在这种情况下也可能是一个值类型,例如int,它不能是null。您应该指定类型约束,将T 限制为类:

...T defaultValueIfNull = null) where T : class

另一种方法是使用...T defaultValueIfNull = default(T)) - 您不需要约束,但值类型默认为0,而不是null

【讨论】:

    猜你喜欢
    • 2013-12-13
    • 2016-11-24
    • 2022-08-13
    • 2021-08-19
    • 2021-06-24
    • 2021-10-28
    • 2021-11-12
    • 2022-01-03
    • 2022-01-20
    相关资源
    最近更新 更多