考虑以下代码(VS 16.8.0预览版2.1 C# 9.0预览版):
#nullable enable
using System.Collections.Generic;
class Archive<T> where T : notnull
{
readonly Dictionary<string, T> Dict = new();
public T? GetAt(string key)
{
return Dict.TryGetValue(key, out var value) ? value : default;
}
}
class Manager
{
public int Age { get; set; }
}
class Main34
{
long F3()
{
Archive<long> a = new();
var johnAge = a.GetAt("john");
if (johnAge is null) return -1; // Error CS0037 Cannot convert null to 'long' because it is a non - nullable value type
return johnAge;
}
long F4()
{
Archive<Manager> a = new();
var johnAge = a.GetAt("john");
//if (johnAge is null) return -1;
return johnAge.Age; // Correct ! warning "Derefrencing of a possibly null reference" will be removed if line above unremarked
}
}
我很难理解/解决F3中的错误,似乎编译器认为JohnAge是long
而不是long?
(在VS中悬停验证后)尽管Archive<T>.GetAt
返回的是T?
是否有一种通用的存档方式可以实现我的需求(即返回可空类型的GetAt方法,即使T是非空基本类型,如long)?