我的函数将枚举类型获取为字符串,我需要对其进行验证。
为什么parsedType(s)在这里为空?
var parsedType1 = Type.GetType("System.Windows.TextAlignment.Left");
var parsedType2 = Type.GetType("System.Windows.TextAlignment");
这行得通吗?
var parsedType3 = Type.GetType("System.String");
答案 0 :(得分:7)
第一行将失败,因为System.Windows.TextAlignment.Left
不是类型的名称-它是类型内 field 的名称。
第二行将失败,因为当您为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");
或者您可以在字符串中指定程序集名称:
Type textAlignment = Type.GetType("System.Windows.TextAlignment, PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");