How to use EnumConverter with CsvHelper

后端 未结 4 1354
执念已碎
执念已碎 2020-12-10 18:08

I\'m using CsvHelper to serialize a class to csv file - until here everything works well.

Now I\'m trying to find a way to convert the class\'s enum properties to th

4条回答
  •  [愿得一人]
    2020-12-10 18:58

    This is the solution I made:

    public class CalendarExceptionEnumConverter : DefaultTypeConverter  where T : struct
        {
            public override string ConvertToString(TypeConverterOptions options, object value)
            {
                T result;
                if(Enum.TryParse(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));
            }
        }
    

    and used it as the following:

    Map(m => m.ExceptionEntityType).TypeConverter>();
    

提交回复
热议问题