5

考虑以下代码:

Nullable<DateTime> dt;

dt. <-- Nullable<DateTime>
dt?. <-- DateTime

空传播返回T,而不是Nullable<T>

如何以及为什么?

4

1 回答 1

5

因为如果左侧的?.对象为 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#,但这就是它的行为。

于 2016-11-17T22:39:46.980 回答