从 Type.GetType(string) 获取可空类型的正确方法
Correct way to get nullable type from Type.GetType(string)
如何使用 Type.GetType(string)
从以下字符串中获取可空类型:System.Boolean?
和 System.Nullable<System.Boolean>
?
这两个都是错误的,我不确定正确的方法是什么。
错误我的意思是写 Type.GetType(X)
returns null
如 Type.GetType(string)
的 remarks 中所述:
The name of a generic type ends with a backtick (`) followed by digits representing the number of generic type arguments. The purpose of this name mangling is to allow compilers to support generic types with the same name but with different numbers of type parameters, occurring in the same scope.
For generic types, the type argument list is enclosed in brackets, and the type arguments are separated by commas.
因此,要从 string
中获取 bool?
的 System.Type
,您需要使用以下内容:
Type.GetType("System.Nullable`1[System.Boolean]");
其中:
System.Nullable
是通用类型名称。
`1
标识通用参数的数量 (1)。
[System.Boolean]
指定泛型参数。
如何使用 Type.GetType(string)
从以下字符串中获取可空类型:System.Boolean?
和 System.Nullable<System.Boolean>
?
这两个都是错误的,我不确定正确的方法是什么。
错误我的意思是写 Type.GetType(X)
returns null
如 Type.GetType(string)
的 remarks 中所述:
The name of a generic type ends with a backtick (`) followed by digits representing the number of generic type arguments. The purpose of this name mangling is to allow compilers to support generic types with the same name but with different numbers of type parameters, occurring in the same scope.
For generic types, the type argument list is enclosed in brackets, and the type arguments are separated by commas.
因此,要从 string
中获取 bool?
的 System.Type
,您需要使用以下内容:
Type.GetType("System.Nullable`1[System.Boolean]");
其中:
System.Nullable
是通用类型名称。
`1
标识通用参数的数量 (1)。
[System.Boolean]
指定泛型参数。