2015-02-09 88 views
2

我有以下枚举(这是从XSD生成):的TryParse工作,但我认为它不应该

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] 
[System.SerializableAttribute()] 
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.ebutilities.at/invoice/02p00")] 
[System.Xml.Serialization.XmlRootAttribute("Sector", Namespace = "http://www.ebutilities.at/invoice/02p00", IsNullable = false)]public enum  
SectorType 
{ 
    [System.Xml.Serialization.XmlEnumAttribute("01")] 
    Item01, 
    [System.Xml.Serialization.XmlEnumAttribute("02")] 
    Item02, 
    [System.Xml.Serialization.XmlEnumAttribute("03")] 
    Item03, 
    [System.Xml.Serialization.XmlEnumAttribute("04")] 
    Item04, 
    [System.Xml.Serialization.XmlEnumAttribute("05")] 
    Item05, 
    [System.Xml.Serialization.XmlEnumAttribute("06")] 
    Item06, 
    [System.Xml.Serialization.XmlEnumAttribute("07")] 
    Item07, 
    [System.Xml.Serialization.XmlEnumAttribute("08")] 
    Item08, 
    [System.Xml.Serialization.XmlEnumAttribute("09")] 
    Item09, 
    [System.Xml.Serialization.XmlEnumAttribute("99")] 
    Item99, 
} 

所以我想解析字符串SectorType:

string s = "88"; 
SectorType sectorType; 
bool result = Enum.TryParse(s, out sectorType); 

之后我的sectorType是“88”,结果是true。所以转换成功了。另外这是工作的罚款:

SectorType sectorType = (SectorType)Enum.Parse(typeof (SectorType), "88") 

sectorType价值是88

下面是来自调试器的图片:

enter image description here

MSDN提供以下信息:

Enum.TryParse方法

的名称或数字值的字符串表示形式转换一个或多个枚举常量与等价的枚举对象。返回值指示转换是否成功。

显然没有等价的枚举对象(88(或其他数字)!= Item01,..., Item09, Item99)。

我在想Enums是强类型的(见dotnetperls/enums)。 它说:

我们看到,枚举是强类型的。你不能将它们分配给任何值。

但显然在我的例子,我可以任意数量的分配给我的SectorType-枚举,我真的不知道为什么这是工作......

看到它运行在.NET Fiddle

+0

另请注意,您的XML整数值将与您的.NET整数值不同。 'Enum.TryParse'只适用于后者。 – leppie 2015-02-09 10:50:39

回答

2

MSDN pageEnum.TryParse<TEnum>(string value, ...)

如果值是不表示TEnum枚举的底层值的整数的字符串表示,该方法返回枚举构件其基础值值转换为一个完整的类型。如果此行为不受欢迎,请调用IsDefined方法以确保整数的特定字符串表示形式实际上是TEnum的成员。

+0

这正是我错过的...... – stefankmitph 2015-02-09 10:59:36

+1

是的,它并不直观。 '强类型'哲学显然不适用于'.Parse()' – 2015-02-09 11:01:10

相关问题