簡體   English   中英

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

[英]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
}

我正在從文本文件中提取一些數據,該文本文件提供了該類型的符號(例如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值方面還不錯...但是當我嘗試解析char值時, type變量不會解析,而是分配為0


問題:是否可以同時評估charint枚舉值? 如果是這樣,怎么辦?

注意:我不想使用自定義屬性來分配文本值,就像我在其他在線示例中看到的那樣。

您的枚舉具有int作為其基礎類型。 所有值均為int s-字符將轉換為整數。 因此, VendorType.Corporation的值(int)'C'為67。

在線觀看ideone

要將字符轉換為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM