嗨,他有一个DTO对象,该对象具有许多具有不同类型的属性,例如string
,int
或bool
等。
我只想在string
属性周围加上双引号。
在Configuration.ShouldQuote
中,field
参数值已全部转换为string
,因此无法得知DTO的原始类型是否为string
, int
或bool
。
是否有一种方法可以从DTO中找到基础属性类型,以便仅对原本类型为true
的字段从Configuration.ShouldQuote
传回string
? >
public class TestDTO
{
public string Field1 { get; set; }
public int Field2 { get; set; }
public bool Field3 { get; set; }
}
var rawData = new[]
{
new TestDTO { Field1 = "Field1", Field2 = 1, Field3 = true },
new TestDTO { Field1 = "Field2", Field2 = 10, Field3 = false }
};
using (var writer = new StreamWriter("file.csv"))
{
using (var csv = new CsvWriter(writer))
{
csv.Configuration.ShouldQuote = (field, context) =>
{
return field is string; // doesn't work as all fields at this point are strings
};
csv.WriteRecords(rawData);
}
}
答案 0 :(得分:0)
我找不到使用ShouldQuote
的方法,但是使用自定义转换器可能是一个很好的解决方法。
public class QuoteStringConverter : StringConverter
{
public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
{
var innerQuotes = ((string)value).Replace(row.Configuration.QuoteString, row.Configuration.DoubleQuoteString);
var quotedValue = row.Configuration.Quote + innerQuotes + row.Configuration.Quote;
return base.ConvertToString(quotedValue, row, memberMapData);
}
}
关闭引号并将您的转换器添加到TypeConverterCache
var rawData = new[]
{
new TestDTO { Field1 = "Field1", Field2 = 1, Field3 = true },
new TestDTO { Field1 = "Field2", Field2 = 10, Field3 = false }
};
using (var writer = new StreamWriter("file.csv"))
using (var csv = new CsvWriter(writer))
{
csv.Configuration.ShouldQuote = (field, context) => false;
csv.Configuration.TypeConverterCache.AddConverter<string>(new QuoteStringConverter());
csv.WriteRecords(rawData);
}