C# 分析混合值枚举(char和int)
我有一个奇怪的枚举,其中一些值是C# 分析混合值枚举(char和int),c#,parsing,enums,char,type-conversion,C#,Parsing,Enums,Char,Type Conversion,我有一个奇怪的枚举,其中一些值是char,另一些值是int: public enum VendorType{ Corporation = 'C', Estate = 'E', Individual = 'I', Partnership = 'P', FederalGovernment = 2, StateAgencyOrUniversity = 3, LocalGovernment = 4, OtherGovernment = 5
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 type = (VendorType)'C';
在线查看它的工作情况:
编辑:答案是正确的,但我正在添加最终的代码,它需要得到这个工作
// 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;
枚举的基础类型为
int
。所有值都是int
s-字符被转换为整数。因此,VendorType.Corporation
的值为(int)'C'
,即67
在线查看:
要将字符转换为VendorType
,只需强制转换:
VendorType type = (VendorType)'C';
在线查看它的工作情况:
编辑:答案是正确的,但我正在添加最终的代码,它需要得到这个工作
// 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;
哇!这是一个严肃的问题。不管出于什么原因,我忘记了字符赋值被转换为int值。。。因此,为什么不能使用字符串,只能使用char。谢谢你,马克。哇。。。这是一个严肃的问题。不管出于什么原因,我忘记了字符赋值被转换为int值。。。因此,为什么不能使用字符串,只能使用char。谢谢你,马克。