如何在CsvHelper中使用EnumConverter [英] How to use EnumConverter with CsvHelper
问题描述
我正在使用 CsvHelper 将类序列化为csv文件-直到这里一切正常为止.
I'm using CsvHelper to serialize a class to csv file - until here everything works well.
现在,我正在尝试寻找一种方法来将类的枚举属性转换为csv中的int值,因此以后可以将CSV用于批量插入.
Now I'm trying to find a way to convert the class's enum properties to their int value in the csv, so I could use the CSV for bulk insert later.
我在CsvHelper中找到了EnumConverter类,但是由于所有尝试都失败了,所以我不知道如何正确使用它.
I found out the EnumConverter class in CsvHelper but I can't figure out how to properly use it, as all my tries are failing.
这是我的映射类代码
public sealed class MyMapping : CsvClassMap<TradingCalendarException>
{
public MyMapping()
{
EnumConverter enumConverter = new EnumConverter(typeof(CalendarExceptionEntityType));
Map(m => m.ExceptionEntityType).Index(0).Name("EXCEPTION_ENTITY_TYPE").TypeConverter(enumConverter);
Map(m => m.ExceptionEntityIdentifier).Index(1).Name("EXCEPTION_ENTITY_IDENTIFIER");
Map(m => m.OptionType).Index(2).Name("OPTION_TYPE");
Map(m => m.StartDatetime).Index(3).Name("EXCEPTION_START_DATETIME");
Map(m => m.EndDatetime).Index(4).Name("EXCEPTION_END_DATETIME");
Map(m => m.DataSourceType).Index(5).Name("DATA_SOURCE_TYPE");
Map(m => m.Description).Index(6).Name("DESCRIPTION");
}
}
和写作部分
using (StreamWriter file = new StreamWriter(filePath, false, Encoding.UTF8))
{
CsvWriter writer = new CsvWriter(file);
MyMapping mapping = new MyMapping();
writer.Configuration.RegisterClassMap(mapping);
writer.WriteRecords(calendarExceptionList);
}
其余的映射(索引和命名)正常工作,只是EnumConverter并没有做任何更改.
The rest of the mapping (indexing and naming) is working, it's just the EnumConverter that doesn't do any change.
我没有在网上找到任何示例.
I didn't find any examples online.
谢谢!
推荐答案
这是我提出的解决方案:
This is the solution I made:
public class CalendarExceptionEnumConverter<T> : DefaultTypeConverter where T : struct
{
public override string ConvertToString(TypeConverterOptions options, object value)
{
T result;
if(Enum.TryParse<T>(value.ToString(),out result))
{
return (Convert.ToInt32(result)).ToString();
}
throw new InvalidCastException(String.Format("Invalid value to EnumConverter. Type: {0} Value: {1}",typeof(T),value));
}
}
并将其用作以下内容:
Map(m => m.ExceptionEntityType).TypeConverter<CalendarExceptionEnumConverter<CalendarExceptionEntityType>>();
这篇关于如何在CsvHelper中使用EnumConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!