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

one*_*mer 1 c# enums parsing type-conversion char

我有一个古怪的枚举,其中一些价值观char和其他int:

public enum VendorType{
    Corporation = 'C',
    Estate = 'E',
    Individual = 'I',
    Partnership = 'P',
    FederalGovernment = 2,
    StateAgencyOrUniversity = 3,
    LocalGovernment = 4,
    OtherGovernment = 5
}
Run Code Online (Sandbox Code Playgroud)

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

我用来做这个的代码是:

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

到目前为止,在解析int值时非常好......但是当我尝试解析char值时,type变量不会解析并被分配0.


问题:是否可以评估两者charint枚举值?如果是这样,怎么样?

注意:我不想使用自定义属性来分配文本值,就像我在网上其他一些hack-ish示例中看到的那样.

Mar*_*ers 9

你的枚举有int其基础类型.所有值都是ints - 字符转换为整数.所以VendorType.Corporation它的值(int)'C'是67.

在线查看:ideone

要将角色转换为VendorType你只需要施放:

VendorType type = (VendorType)'C';
Run Code Online (Sandbox Code Playgroud)

看到它在线工作: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;
Run Code Online (Sandbox Code Playgroud)