代码之家  ›  专栏  ›  技术社区  ›  itminus

C#default(TValue?)返回default(TVvalue)

  •  2
  • itminus  · 技术社区  · 3 年前

    我知道 default(bool?) 退货 null :

    var msg = default(bool?) is null ? 
        "default(bool?) is NULL":                   
        "default(bool?) is NOT NULL";
    // msg == "default(bool?) is NULL"
    

    但是,在处理泛型Type参数时,会导致令人困惑的结果。

    考虑以下通用方法:

    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;
    }
    
    

    上面的代码返回 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;
    

    我的问题是:为什么 默认值(bool?) 退货 无效的 而泛型 默认值(T值?) 具有 TValue = bool 退货 false ?

    0 回复  |  直到 3 年前