C# 默认值(TValue?) 返回默认值(TValue)

itm*_*nus 5 .net c# .net-core asp.net-core

我知道default(bool?)回报null

var msg = default(bool?) is null ? 
    "default(bool?) is NULL":                   
    "default(bool?) is NOT NULL";
// msg == "default(bool?) is NULL"
Run Code Online (Sandbox Code Playgroud)

然而,当处理泛型类型参数时,它会导致令人困惑的结果。

考虑如下通用方法:

static TValue? GetProcItem<TValue>(IDictionary<string, JToken> cache, string key)
{
    if(cache.TryGetValue(key, out var jtoken))
    {
        var value = jtoken.ToObject<TValue>();
        return value;
    }

    // if the key does not exist
    TValue? ret = default(TValue?);  
    return ret;
}

Run Code Online (Sandbox Code Playgroud)

上面的代码返回default(TValue?)不适用于bool指定的泛型类型:

var cache = new Dictionary<string, JToken>();

// the compiler infers that xBool is a boolean type instead of `bool?
var xBool = GetProcItem<bool>(cache, "a-key-that-does-not-exist"); 

// the runtime value of xBool is also a `boolean` type instead of `bool?`.
Console.WriteLine($"default(bool?)={xBool}; ");


//////////// the output is: /////////////////////////////
//////////// default(bool?)=False;
Run Code Online (Sandbox Code Playgroud)

我的问题是:为什么default(bool?)会返回null而泛型default(TValue?)TValue = bool返回false