How to use EnumConverter with CsvHelper

后端 未结 4 1364
执念已碎
执念已碎 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 18:55

    This is how I did it for the latest version of CSV Helper which is 7.1.1:

    public class AggregateEnumConverter : EnumConverter where T : struct
    {
        public AggregateEnumConverter() : base(typeof(T)) { }
    
        public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
        {
            if(!Enum.TryParse(text, out AggregateType aggregateType))
            {
                // This is just to make the user life simpler...
                if(text == "24HAVG")
                {
                    return AggregateType._24HAVG;
                }
    
                // If an invalid value is found in the CSV for the Aggregate column, throw an exception...
                throw new InvalidCastException($"Invalid value to EnumConverter. Type: {typeof(T)} Value: {text}");
            }
    
            return aggregateType;
        }
    }
    

    Note: the code above is making use of C# 7 new inline out variables.
    More info here: How should I convert a string to an enum in C#?

    This is how you make use of the custom EnumConverter:

    /// 
    /// Maps Tag class properties to the CSV columns' names
    /// 
    public sealed class TagMap : ClassMap
    {
        public TagMap(ILogger logger)
        {
            Map(tag => tag.Aggregate).Name("aggregate").TypeConverter>();
        }
    }
    

提交回复
热议问题