【问题标题】:Is there a way to suppress a property when writing out a file with FileHelpers?使用 FileHelpers 写出文件时,有没有办法抑制属性?
【发布时间】:2016-09-14 19:59:38
【问题描述】:

有没有办法在使用 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 中使用一个属性来禁止写出文件吗?

【问题讨论】:

    标签: c# filehelpers


    【解决方案1】:

    根据文档 herehere,您将使用 FieldValueDiscarded 属性。这是完整的简介:

    对不使用的字段使用 FieldValueDiscarded 属性。

    如果你的记录类有一些没有使用的字段,库会丢弃这个属性标记的字段的值

    【讨论】:

    • 这似乎只适用于字段而不是属性。我将不得不解决一些问题,因为当我将属性转换为字段时出现错误。我使用的类有 70 多个属性。
    【解决方案2】:

    作为一种解决方法,您可以使用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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-25
      • 1970-01-01
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      相关资源
      最近更新 更多