我有一个奇怪的枚举,其中一些值为char
,另一些为int
:
public enum VendorType{
Corporation = 'C',
Estate = 'E',
Individual = 'I',
Partnership = 'P',
FederalGovernment = 2,
StateAgencyOrUniversity = 3,
LocalGovernment = 4,
OtherGovernment = 5
}
我正在从文本文件中提取一些数据,该文本文件提供了该类型的符号(例如
I
或4
),并且使用它来查找枚举的硬类型值(例如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
。问题:是否可以同时评估
0
和char
枚举值?如果是这样,怎么办?注意:我不想使用自定义属性来分配文本值,就像我在其他在线示例中看到的那样。
最佳答案
您的枚举具有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/