【问题标题】:Type of enum can't be created from string [duplicate]无法从字符串创建枚举类型 [重复]
【发布时间】:2019-04-16 17:12:14
【问题描述】:

我的函数获取枚举类型作为我需要验证的字符串。

为什么 parsedType(s) 在这里为空?

var parsedType1 = Type.GetType("System.Windows.TextAlignment.Left");
var parsedType2 = Type.GetType("System.Windows.TextAlignment");

虽然这行得通?

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

【问题讨论】:

    标签: c# enums


    【解决方案1】:

    第一行会失败,因为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");
    

    或者您可以在字符串中指定程序集名称:

    Type textAlignment = Type.GetType("System.Windows.TextAlignment, PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
    

    【讨论】:

      猜你喜欢
      • 2011-01-01
      • 1970-01-01
      • 2015-11-09
      • 2019-10-14
      • 1970-01-01
      • 2020-03-09
      • 2014-07-23
      相关资源
      最近更新 更多