2012-03-15 59 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