C# 枚举类型可以';不能从字符串创建

C# 枚举类型可以';不能从字符串创建,c#,enums,C#,Enums,我的函数将枚举类型作为字符串获取,我需要对其进行验证 为什么这里的parsedType为空 var parsedType1 = Type.GetType("System.Windows.TextAlignment.Left"); var parsedType2 = Type.GetType("System.Windows.TextAlignment"); 虽然这样行吗 var parsedType3 = Type.GetType("System.String"); 第一行将失败,因为Syst

我的函数将枚举类型作为字符串获取,我需要对其进行验证

为什么这里的parsedType为空

var parsedType1 = Type.GetType("System.Windows.TextAlignment.Left");
var parsedType2 = Type.GetType("System.Windows.TextAlignment");
虽然这样行吗

var parsedType3 = Type.GetType("System.String");

第一行将失败,因为
System.Windows.TextAlignment.Left
不是类型的名称,而是类型中某个字段的名称

第二行将失败,因为当您仅提供一个类型名而不提供任何程序集部分时,它会查找当前正在执行的程序集和
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");