我的函数将枚举类型获取为字符串,我需要对其进行验证。
为什么parsedType(s)在这里为null?
var parsedType1 = Type.GetType("System.Windows.TextAlignment.Left");
var parsedType2 = Type.GetType("System.Windows.TextAlignment");
Run Code Online (Sandbox Code Playgroud)
虽然这个有效吗?
var parsedType3 = Type.GetType("System.String");
Run Code Online (Sandbox Code Playgroud)
第一行将失败,因为System.Windows.TextAlignment.Left这不是类型的名称-它是类型内字段的名称。
第二行将失败,因为当您Type.GetType(string)仅提供类型名称而没有任何程序集部件时,它会在当前正在执行的程序集和中查找mscorlib。这就是为什么"System.String"。
如果您知道类型将在哪个程序集中,请Assembly.GetType(string)改用。
例如:
// Here TextDataFormat is just another type that's in the same assembly
Type textAlignment = typeof(TextDataFormat).Assembly.GetType("System.Windows.TextAlignment");
Run Code Online (Sandbox Code Playgroud)
或者,您可以在字符串中指定程序集名称:
Type textAlignment = Type.GetType("System.Windows.TextAlignment, PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
101 次 |
| 最近记录: |