c# - 尝试写入空十进制值时出现 Filehelpers NullReferenceException

标签 c# .net nullreferenceexception filehelpers

使用 FileHelpers 库时,我在尝试编写 .csv 文件时收到 NullReferenceException。

我已经缩小了问题范围。每当我有一个空小数?它抛出这个异常。它在阅读时效果很好,但在写作时效果不佳。

我提供了一个示例,它显示了与我的应用相同的问题:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication11
{
   class Program
   {
      static void Main(string[] args) {
         rec record = new rec { id = 1, mydecimal = null };
         List<rec> records = new List<rec> { record };

         FileHelpers.FileHelperEngine<rec> engine = new FileHelpers.FileHelperEngine<rec>();

         Console.WriteLine(engine.WriteString(records));

      }
   }

   [FileHelpers.DelimitedRecord(",")]
   public class rec
   {
      public int id;
      public decimal? mydecimal;

   }
}

最佳答案

您可以使用自定义转换器。

public class NullableDecimalConverter : FileHelpers.ConverterBase
{
    public override object StringToField(string from)
    {
        return from;
    }

    public override string FieldToString(object fieldValue)
    {
        if (fieldValue == null)
            return String.Empty;
        return fieldValue.ToString();
    }
}

您需要修改记录类以将 [FieldConverter()] 属性添加到任何 decimal? 字段。

[FileHelpers.DelimitedRecord(",")]
public class rec
{
    public int id;

    [FileHelpers.FieldConverter(typeof(NullableDecimalConverter))]
    public decimal? mydecimal;

}

关于c# - 尝试写入空十进制值时出现 Filehelpers NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8044396/

相关文章:

javascript - 部署时为 "That assembly does not allow partially trusted callers"

c# - 结构相等性如何与 Int32 一起使用?

c# - 未将对象引用设置为对象的实例 asp.net

c# - 更改跟踪在 Entity Framework 中的工作原理

c# - UWP - 不可选择的 NavigationViewItem 但可点击

.net - = 和 := 有什么区别

asp.net-mvc-4 - 单击发布时出错 | "Object reference not set to an instance of an object"

c# - NavigationController 颜色和左键

c# - 表单提交后处理刷新

C# 递归方法返回空引用,对象引用未设置为对象的实例。 XElement 对象