[英]Is It possible to take one enum list and convert it to another?
我想获取提供的enum
列表并将其转换为我的列表。 我从服务类型获取列表,然后我想通过DocumentFieldTypeConverter()
将其转换为我的FieldTyp
但是,这个凹痕有效,因为此时enum
无效dic.Add(i, Enum.GetName(rgl, FieldType));
我第一次尝试这个,如果这完全是胡说八道,我深表歉意。 在此之前,我只使用过开关控制,但我认为可能会有更好的东西
class Program {
static void Main(string[] args) {
var x = new Type().DocumentFieldTypeConverter();
foreach(var kvp in x) {
Console.WriteLine($ "{kvp.Key}: {kvp.Value}");
}
Console.ReadLine();
}
}
public static class EnumExtension {
public static Dictionary < int,
FieldType > DocumentFieldTypeConverter(this Type rglFieldType) {
var dic = new Dictionary < int,
FieldType > ();
var rgl = type.GetType();
foreach(int i in Enum.GetValues(rgl)) {
dic.Add(i, Enum.GetName(rgl, FieldType));
}
return dic;
}
}
public enum FieldType {
Document_Class_Code,
Document,
Document_Number,
DocumentType,
Passport_Number,
Invitation_Number,
}
public enum Type {
Document_Class_Code,
Document,
Document_Number,
DocumentType,
Passport_Number,
Invitation_Number,
}
Type
是一个关键字,所以我建议为第二个枚举使用另一个名称。
这里有一些方法,我建议使用Enum.TryParse
来检查转换。
public enum FieldType
{
Document_Class_Code,
Document,
Document_Number,
DocumentType,
Passport_Number,
Invitation_Number,
}
public enum FieldTypeCopy
{
Document_Class_Code,
Document,
Document_Number,
DocumentType,
Passport_Number,
Invitation_Number,
}
FieldType fieldType = FieldType.DocumentType;
// Explicit conversion using the order
int i = (int)fieldType;
FieldTypeCopy fieldTypeCopy1 = (FieldTypeCopy)i;
Console.WriteLine("Copy 1: " + fieldTypeCopy1.ToString());
// Parse without check
FieldTypeCopy fieldTypeCopy2 = (FieldTypeCopy)Enum.Parse(typeof(FieldType), fieldType.ToString(), true);
Console.WriteLine("Copy 2: " + fieldTypeCopy2.ToString());
// Parse with check
if (Enum.TryParse(fieldType.ToString(), out FieldTypeCopy fieldTypeCopy3))
{
Console.WriteLine("Copy 3: " + fieldTypeCopy3.ToString());
}
else
{
Console.WriteLine("Unable to Parse value to enum");
}
使用下面的通用 function 来转换枚举 -
public static class EnumExtension
{
public static Dictionary<int, TDestinationType> EnumTypeConverter<TSourceType, TDestinationType>()
where TSourceType : struct, IConvertible
where TDestinationType : struct, IConvertible
{
var dictionary = new Dictionary<int, TDestinationType>();
var sourceEnum = typeof(TSourceType);
var sourceValues = Enum.GetValues(sourceEnum);
foreach (int enumVal in sourceValues)
{
var enumString = enumVal.ToString();
var destinationEnum = Enum.Parse(typeof(TDestinationType), enumString);
dictionary.Add(enumVal, (TDestinationType)destinationEnum);
}
return dictionary;
}
}
从 main 调用它为 -
public static void Main(string[] args)
{
var enumVals = EnumExtension.EnumTypeConverter<Type, FieldType>();
foreach (var enumVal in enumVals)
{
Console.WriteLine($"{enumVal.Key}: {enumVal.Value}");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.