CsvHelper for saving an object of a derived class from an abstract class

[Serializable]
public abstract class AbstractModel : ObservableObject
{
    // nothing.
}

public class RealModel : AbstractModel 
{
    public string PropertyA {get; set;}
    public string PropertyB {get; set;}
}

Please note that ObservableObject- from Mvvm-light.

With the above models, I used CsvHelper as shown below.

AbstractModel instance = new RealModel()
                             {
                                 PropertyA = "foo",
                                 PropertyA = "bar"
                             };

using (TextWriter file = new StreamWriter("path"))
using (var csv = new CsvWriter(file))
{
    csv.WriteRecord(instance);
}

It throws an error as shown below:

No properties are displayed for type 'AbstractModel'

It works great when I install RealModel instance = new RealModel();. But I have different derived classes and you want to save them in one save method.

How can i do this?

+4
source share
1 answer

, , . XML, CSV . CSV ( , CSV ).

.

CSV 1 ():

ID,GivenName,FamilyName
1,John,A
2,Mike,B

CSV- 2 ( "" ):

Date,Anniversary
1.1.,New year

CSV " "; , ? ? "" ""? ?

. , CSV . . , ( ).

: ( , ):

1,John,A
1.1.,New year
2,Mike,B

, ? , " CSV", , . , .

, , ( , , - ). .

:

public abstract class AbstractModel : ObservableObject
{
    // no property

    protected string Prefix(object data)
    {
       if (ReferenceEquals(data, null))
         return string.Empty;
       string result = data.ToString();
       if (data.Contains(",") || data.Contains("\""))
         return $"\"{data}\"";
       return data;
    }

}

public class RealModel : AbstractModel 
{
    public string PropertyA {get; set;}
    public string PropertyB {get; set;}

    public override string ToString()
    {
       return $"{Prefix(PropertyA)},{Prefix(PropertyB)}";
    }
}

:

using (StreamWriter file = new StreamWriter("path"))
{
  foreach (AbstractModel instance in allInstances)
    file.WriteLine(instance);
}
0

Source: https://habr.com/ru/post/1622890/


All Articles