为什么使用 [var x = new T()] 解析为 [T?]?

Why is the use of [var x = new T()] resolving to [T?]?

我正在使用 VS2022、.NET 6、C# 10,并在整个项目范围内启用了可空性上下文。

public static ModelEnumerationAttributeProperty FromPropertyInfo (PropertyInfo propertyInfo, object value)
{
    var property = ModelEnumerationAttributeProperty.FromPropertyInfo(propertyInfo);

    property.PropertyValue = value;
    property.PropertyValueString = value?.ToString();

    return (property);
}

变量 property 的自动检测类型正在解析为可空类型 ModelEnumerationAttributeProperty?

这似乎是对原版 class 的简单构造函数调用。构造函数可以抛出异常但不能 return null.

那么为什么使用 [var x = new T()] 会自动解析为

更新:* 这是调用构造函数的静态重载:

public static ModelEnumerationAttributeProperty FromPropertyInfo (PropertyInfo propertyInfo)
{
    var property = new ModelEnumerationAttributeProperty();

    property.PropertyInfo = propertyInfo;
    property.Type = propertyInfo.PropertyType;
    property.Name = propertyInfo.PropertyType.Name;
    property.FullName = propertyInfo.PropertyType.FullName ?? "";
    property.AssemblyQualifiedName = propertyInfo.PropertyType.AssemblyQualifiedName ?? "";

    property.PropertyName = propertyInfo.Name;

    return (property);
}

如果不可为空,编译器不会标记此重载和 return 类型。我还不如调用 var o = new object();,它会做同样的事情。

这是由语言定义的。

来自the documentation for var

Important

When var is used with nullable reference types enabled, it always implies a nullable reference type even if the expression type isn't nullable. The compiler's null state analysis protects against dereferencing a potential null value. If the variable is never assigned to an expression that maybe null, the compiler won't emit any warnings. If you assign the variable to an expression that might be null, you must test that it isn't null before dereferencing it to avoid any warnings.