Enum 的 TryParse 正在运行,但我认为它不应该

TryParse of Enum is working, but I think it shouldn't

我有以下枚举(从 xsd 生成):

[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

这是来自调试器的图片:

MSDN 提供了以下信息:

Enum.TryParse Method

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. The return value indicates whether the conversion succeeded.

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

我认为枚举是强类型的(参见 dotnetperls/enums)。 它说:

We see that enums are strongly-typed. You cannot assign them to just any value.

但在我的示例中很明显,我可以为我的 SectorType-Enum 分配任何数字,但我真的不知道为什么会这样...

.NET Fiddle 查看 运行。

来自 MSDN page for Enum.TryParse<TEnum>(string value, ...):

If value is the string representation of an integer that does not represent an underlying value of the TEnum enumeration, the method returns an enumeration member whose underlying value is value converted to an integral type. If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of TEnum.