2012-03-15 85 views
1

我有一个古怪枚举其中一些值是char和其他int解析混合值枚举(char和INT)

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

我在一些数据从文本文件中,提供了符号猛拉(例如I4),我用它来查找枚举的硬键入值(分别为VendorType.IndividualVendorType.LocalGovernment)。

我使用的这个过程的代码是:

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

当谈到解析int值...但到目前为止好,当我尝试分析chartype变量没有按” t解析并被分配0


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

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

回答

7

您的枚举有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; 
+0

哇......这是一个严重的旋钮问题。无论出于何种原因,我忘记了将字符赋值转换为int值......因此,为什么不能使用字符串,只能使用char。谢谢马克。 – 2012-03-15 18:47:55