[英]Is there a way to suppress a property when writing out a file with FileHelpers?
使用FileHelpers寫入文件時,是否可以抑制屬性?
說我有一個對象:
[DelimitedRecord(",")]
public class MyClass
{
public int Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
public string Field4 { get; set; }
public string Field5 { get; set; }
}
我想寫出一個csv,但我想省略Field3(無論是否填充)。
例如
輸出將是:Field1,Field2,Field4,Field5
我可以在FileHelpers中使用某個屬性來禁止寫出文件嗎?
解決方法是,可以使用AfterWrite
事件刪除最后一個定界符。 像這樣:
[DelimitedRecord(",")]
class Product : INotifyWrite
{
[FieldQuoted(QuoteMode.AlwaysQuoted)]
public string Name;
[FieldQuoted(QuoteMode.AlwaysQuoted)]
public string Description;
[FieldOptional]
public string Size;
public void BeforeWrite(BeforeWriteEventArgs e)
{
// prevent output of [FieldOptional] Size field
Size = null;
}
public void AfterWrite(AfterWriteEventArgs e)
{
// remove last "delimiter"
e.RecordLine = e.RecordLine.Remove(e.RecordLine.Length - 1, 1);
}
}
class Program
{
static void Main(string[] args)
{
var engine = new FileHelperEngine<Product>();
var products = new Product[] { new Product() { Name = "Product", Description = "Details", Size = "Large"} };
var productRecords = engine.WriteString(products);
try
{
// Make sure Size field is not part of the output
Assert.AreEqual(@"""Product"",""Details""" + Environment.NewLine, productRecords);
Console.WriteLine("All tests pass");
}
catch (Exception ex)
{
Console.WriteLine("An error occurred");
Console.WriteLine(ex);
}
Console.ReadKey();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.