如何判断C#属性类型是string还是可空string(string?)?
判断.NET可空引用类型的源码类型(string vs string?)
现象原因
- 值类型(如int)的可空形式
int?编译后会被包装为Nullable<int>(即System.Nullable<System.Int32>),反射获取的PropertyType与int完全不同,所以输出False。 - 引用类型(如string)的可空形式
string?只是编译时的注解标记,运行时类型仍为string,反射拿到的PropertyType和非可空引用类型一致,因此输出True。
解决方案:读取Nullable元数据
要判断源码中属性是否为可空引用类型,需要通过System.Reflection.NullabilityInfoContext读取编译时嵌入的nullable元数据,示例代码如下:
var t = typeof(Sample); var p1 = t.GetProperty(nameof(Sample.Str1))!; var p2 = t.GetProperty(nameof(Sample.Str2))!; var nullabilityContext = new NullabilityInfoContext(); // 获取属性的可空信息 var p1Nullability = nullabilityContext.Create(p1); var p2Nullability = nullabilityContext.Create(p2); // 判断属性在源码中是否为可空引用类型 Console.WriteLine(p1Nullability.ReadState == NullabilityState.Nullable); // 输出 False Console.WriteLine(p2Nullability.ReadState == NullabilityState.Nullable); // 输出 True public class Sample { public string Str1 { get; set; } = default!; public string? Str2 { get; set; } }
说明
NullabilityInfoContext会解析编译时生成的nullable元数据,通过ReadState(针对属性的读取状态)或WriteState(针对属性的写入状态)的枚举值判断可空性。- 该方法要求项目启用
<Nullable>enable</Nullable>,且目标框架为.NET Core 3.0、.NET 5及以上版本。
内容的提问来源于stack exchange,提问作者HamedH
相关产品推荐
相关产品推荐

