我有一个用例,在写实际数据之前,我需要写两行标题。
例如
标题,标题
姓名,截至目前的年龄
忍者,28岁
我认为可以使用ClassMap实现来实现。 但是当它引发我stackoverflow异常时。
我的尝试如下:
[TestMethod]
public void WriteMappedHeaders()
{
var data = new List<Data> {
new Data { Name ="Ninga", Age=24 },
};
using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer))
{
csv.Configuration.RegisterClassMap<HeaderConstMap>();
csv.Configuration.RegisterClassMap<DataMap>();
csv.WriteHeader<HeaderConstMap>();
csv.NextRecord();
csv.WriteRecords(data);
writer.Flush();
var result = writer.ToString();
var expected = new StringBuilder();
expected.AppendLine("Header,Header");
expected.AppendLine("FullName,Age as of now");
expected.AppendLine("Ninja,24");
Assert.AreEqual(expected.ToString(), result);
}
}
public class HeaderConst
{
public string Header1 { get; set; }
public string Header2 { get; set; }
}
public class HeaderConstMap : ClassMap<HeaderConst>
{
public HeaderConstMap()
{
Map(m => m.Header1).Index(0).Name("Header");
Map(m => m.Header2).Index(1).Name("Header");
}
}
public class Data
{
public string Name { get; set; }
public int Age { get; set; }
}
public class DataMap : ClassMap<Data>
{
public DataMap()
{
Map(m => m.Name).Index(0).Name("FullName");
Map(m => m.Age).Index(1).Name("Age as of now");
}
}
在我打电话的那一行抛出的异常
csv.WriteHeader<HeaderConstMap>();
很高兴有人可以给我积极的态度来解决此问题。
RSF
答案 0 :(得分:0)
我找到了答案: 实际上我做错了事。
但是,只是发布解决方案以使他人受益。
[TestMethod]
public void WriteMappedHeaders()
{
var data = new List<Data> {
new Data { Age=24, Name="Ninja"},
new Data { Age=25, Name="Kid"}
};
var headers = new List<HeaderConst>();
using (var writer = new StringWriter())
{
using (var csv = new CsvWriter(writer))
{
csv.Configuration.RegisterClassMap<HeaderConstMap>();
csv.WriteHeader<HeaderConst>();
csv.Configuration.UnregisterClassMap<HeaderConstMap>();
csv.NextRecord();
csv.Configuration.RegisterClassMap<DataMap>();
csv.WriteHeader<Data>();
csv.NextRecord();
csv.WriteRecords(data);
csv.Configuration.UnregisterClassMap<DataMap>();
}
writer.Flush();
var result = writer.ToString();
var expected = new StringBuilder();
expected.AppendLine("Header,Header");
expected.AppendLine("FullName,Age as of now");
expected.AppendLine("Ninja,24");
expected.AppendLine("Kid,25");
Assert.AreEqual(expected.ToString(), result);
}
}
public class HeaderConst
{
public string Header1 { get; set; }
public string Header2 { get; set; }
}
public class HeaderConstMap : ClassMap<HeaderConst>
{
public HeaderConstMap()
{
Map(m => m.Header1).Index(0).Name("Header");
Map(m => m.Header2).Index(1).Name("Header");
}
}
public class Data
{
public string Name { get; set; }
public int Age { get; set; }
}
public class DataMap : ClassMap<Data>
{
public DataMap()
{
Map(m => m.Name).Index(0).Name("FullName");
Map(m => m.Age).Index(1).Name("Age as of now");
}
}