考虑以下代码:
Nullable<DateTime> dt;
dt. <-- Nullable<DateTime>
dt?. <-- DateTime
空传播返回T
,而不是Nullable<T>
。
如何以及为什么?
考虑以下代码:
Nullable<DateTime> dt;
dt. <-- Nullable<DateTime>
dt?. <-- DateTime
空传播返回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#,但这就是它的行为。