c# - 解析混合值枚举(char和int)

标签 c# parsing enums char type-conversion

我有一个奇怪的枚举,其中一些值为char,另一些为int

public enum VendorType{
    Corporation = 'C',
    Estate = 'E',
    Individual = 'I',
    Partnership = 'P',
    FederalGovernment = 2,
    StateAgencyOrUniversity = 3,
    LocalGovernment = 4,
    OtherGovernment = 5
}


我正在从文本文件中提取一些数据,该文本文件提供了该类型的符号(例如I4),并且使用它来查找枚举的硬类型值(例如VendorType.Individual)。

我用于执行此操作的代码是:

var valueFromData = 'C'; // this is being yanked from a File.IO operation.
VendorType type;
Enum.TryParse(valueFromData, true, out type);


到目前为止,在解析VendorType.LocalGovernment值时效果很好...但是当我尝试解析int值时,char变量不会解析,而是被分配为type



问题:是否可以同时评估0char枚举值?如果是这样,怎么办?

注意:我不想使用自定义属性来分配文本值,就像我在其他在线示例中看到的那样。

最佳答案

您的枚举具有int作为其基础类型。所有值均为int-字符将转换为整数。因此VendorType.Corporation的值(int)'C'是67。

在线查看:ideone

要将字符转换为VendorType,您只需要强制转换:

VendorType type = (VendorType)'C';


看到它在线运行:ideone



编辑:答案是正确的,但我要添加完成此工作所需的最终代码。

// this is the model we're building
Vendor vendor = new Vendor(); 

// out value from Enum.TryParse()
VendorType type;

// value is string from File.IO so we parse to char
var typeChar = Char.Parse(value);

// if the char is found in the list, we use the enum out value
// if not we type cast the char (ex. 'C' = 67 = Corporation)
vendor.Type = Enum.TryParse(typeChar.ToString(), true, out type) ? type : (VendorType) typeChar;

关于c# - 解析混合值枚举(char和int),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9726009/

相关文章:

c# - 在sql server之间复制数据库

c# - 在 C# 中实现多于一种类型对象的堆栈的最佳方法是什么?

Android 4.0 Ice Cream Sandwich 解析器错误

java - 获取正在运行的服务(LINUX JAVA): how to parse service name only?

java - 为什么 Java 在只识别最后一个时允许引用两个(或更多)枚举?

c# - 如何查找 List<Dictionary<string, object>> 中的重复值?

c# - 如何合并两个列表的内容?

java - 将 URI 字符串解析为名称-值集合

swift - 您如何反射(reflect) Codable/Codable Keys 协议(protocol)的设计?

java - 当定义为泛型类参数时,如何获取 Enum 的 valueOf 和值并调用其实现的接口(interface)上的方法