Search code examples
c#csvhelper

How to make class generic to pass dynamic property class in c#


I have demo code which ignores the Extra property. I need to make this class generic.

public class HelloFriend 
{
    public static void Main(string[] args)
    {
        var s = new StringBuilder();
        s.Append("Id,Name\r\n");
        s.Append("1,one\r\n");
        s.Append("2,two\r\n");
        using (var reader = new StringReader(s.ToString()))
        using (var csv = new CsvReader(reader))
        {
            csv.Configuration.RegisterClassMap<TestMap>();
            csv.GetRecords<Test>().ToList();
        }
    }
}

public class Test : Test1
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public abstract class Test1
{
    public decimal Extra { get; set; }
}

public class TestMap : CsvClassMap<Test>
{
    public TestMap()
    {
        AutoMap();
        Map(m => m.Extra).Ignore();
    }
}

As shown in above code if I need to use different Test1, or Test2 instead of Test, then I need to write another TestMap class. How can I avoid this? How can I make this class generic, so I can pass multiple classes like Test to ignore the Extra property?


Solution

  • Do you mean somehting like this?

    class Program
    {
        public static void Main(string[] args)
        {
            var s = new StringBuilder();
            s.Append("Id,Name\r\n");
            s.Append("1,one\r\n");
            s.Append("2,two\r\n");
            using (var reader = new StringReader(s.ToString()))
            using (var csv = new CsvReader(reader))
            {
                csv.Configuration.RegisterClassMap<TestMap<Test>>();
                csv.GetRecords<Test>().ToList();
            }
        }
    }
    public class Test : Test1
    {
        public int Id { get; set; }
        public string Name { get; set; }
    
    }
    
    public Abstract class Test1 
    {
       public decimal Extra { get; set; }
    }
    
    
    public class Test2 : Test1
    {
        //other propertys
    }
    
    
    public class TestMap<T> : CsvClassMap<T> where T : Test1
    {
        public TestMap()
        {
            AutoMap();
    
                Map(m => m.Extra).Ignore();
    
        }
    }