c# - Enum 的 TryParse 正在工作,但我认为它不应该

标签 c# parsing enums tryparse

我有以下枚举(从 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 .

这是来自调试器的图片:

enter image description here

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/

相关文章:

c# - 使用 .NET-Standard 2.0 项目构建 ASP.NET-Core 3.1 会导致冲突的 Microsoft.AspNetCore.Mvc.Analyzers 程序集

c# - 绑定(bind)在没有 INotifyPropertyChanged 的​​情况下工作,为什么?

c++ - 绑定(bind)到枚举的类成员

PostgreSQL:更改枚举类型的列

python - 在 python 中编写一个快速解析器

c++ - C++ 中的标记和枚举分派(dispatch)有什么区别?

c# - 连接字符串的最有效方法?

c# - 如何绑定(bind)数据列表控件的项目模板字段内的下拉列表

从不完整的字符串解析 golang 时间对象

php - 在 PHP 调用中将 vector 发送到 C++ 程序并读取它