为什么 Nullable<T> return T 而不是 Nullable<T> 的空值传播?
Why does null-propagation of Nullable<T> return T and not Nullable<T>?
考虑以下代码:
Nullable<DateTime> dt;
dt. <-- Nullable<DateTime>
dt?. <-- DateTime
空传播 returns T
,而不是 Nullable<T>
。
如何以及为什么?
由于 null 传播的工作方式,如果 ?.
左侧的对象为 null,则永远不会执行右侧的对象。因为您知道右侧永远不会为空,所以为了方便起见,它去掉了 Nullable
,这样您就不需要每次都输入 .Value
。
你可以把它想象成
public static T operator ?.(Nullable<U> lhs, Func<U,T> rhs)
where T: class
where U: struct
{
if(lhs.HasValue)
{
return rhs(lhs.Value);
}
else
{
return default(T);
}
}
以上代码不是合法的 C#,但这是它的行为。
考虑以下代码:
Nullable<DateTime> dt;
dt. <-- Nullable<DateTime>
dt?. <-- DateTime
空传播 returns T
,而不是 Nullable<T>
。
如何以及为什么?
由于 null 传播的工作方式,如果 ?.
左侧的对象为 null,则永远不会执行右侧的对象。因为您知道右侧永远不会为空,所以为了方便起见,它去掉了 Nullable
,这样您就不需要每次都输入 .Value
。
你可以把它想象成
public static T operator ?.(Nullable<U> lhs, Func<U,T> rhs)
where T: class
where U: struct
{
if(lhs.HasValue)
{
return rhs(lhs.Value);
}
else
{
return default(T);
}
}
以上代码不是合法的 C#,但这是它的行为。