[英]Parsing mixed value enums (char and int)
我有一個奇怪的枚舉,其中一些值是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
和VendorType.LocalGovernment
)。
我用於執行此操作的代碼是:
var valueFromData = 'C'; // this is being yanked from a File.IO operation.
VendorType type;
Enum.TryParse(valueFromData, true, out type);
到目前為止,在解析int
值方面還不錯...但是當我嘗試解析char
值時, type
變量不會解析,而是分配為0
。
問題:是否可以同時評估char
和int
枚舉值? 如果是這樣,怎么辦?
注意:我不想使用自定義屬性來分配文本值,就像我在其他在線示例中看到的那樣。
您的枚舉具有int
作為其基礎類型。 所有值均為int
s-字符將轉換為整數。 因此, VendorType.Corporation
的值(int)'C'
為67。
要將字符轉換為VendorType
您只需要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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.