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

时间:2012-03-15 18:37:22

标签: 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)中查找一些数据,并使用它来查找枚举的硬类型值(ex分别是VendorType.IndividualVendorType.LocalGovernment

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

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

到目前为止解析int值时非常好......但是当我尝试解析char值时,type变量不会解析并被赋值{ {1}}。


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

注意:我不想使用自定义属性来分配文本值,就像我在其他一些黑客网上看到的那样。

1 个答案:

答案 0 :(得分:8)

您的枚举有int作为其基础类型。所有值都是int s - 字符转换为整数。因此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;
相关问题