我有以下枚举(从 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对于 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.
关于c# - Enum 的 TryParse 正在工作,但我认为它不应该,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28407824/