2015-02-09 62 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

相關問題