你能告诉反射哪个字符串是可空的,哪个不是吗?



我有这两种类型:

  1. Type nrvt = typeof(List<string?>);//可空字符串通用参数
  2. Type nnrvt = typeof(List<string>);//非空字符串泛型参数

我可以告诉(通过反射).NET 6中有可空的和非可空的字符串吗?

有一个NullabilityInfoContext但处理对象相关的东西(属性,字段,事件和参数)

No。两个结构的IL是相同的(SharpLab链接):

IL_0000: nop
IL_0001: ldtoken class [System.Collections]System.Collections.Generic.List`1<string>
IL_0006: call class [System.Runtime]System.Type [System.Runtime]System.Type::GetTypeFromHandle(valuetype [System.Runtime]System.RuntimeTypeHandle)
IL_000b: stloc.0
IL_000c: ret

,其中局部变量0为class [System.Runtime]System.Type。因此,在编译时,这两个表达式之间没有区别。

不,nrvtnnrvt是同一类型。

Nullable引用类型只是一个编译器指令,目的是防止关于对象在# Nullable上下文中可能为空的警告。

string?不像int?创建Nullable<int>那样创建Nullable<string>。事实上,考虑到Nullable<>where T : struct的类型约束,Nullable<string>甚至不是一个有效的类型。

最新更新