c# - 如果值为空格,则不会调用 FileHelpers FieldConverter

标签 c# filehelpers fixed-length-record

我正在尝试使用 FileHelpers 解析文件。我需要将字段映射到 KeyValuePair,对于其中的一些字段,如果文件中的字符串是空格,则存在映射。但是,当文件中的字符串为空白时,似乎不会调用我的自定义 FieldConverter 的 FieldToString 方法。不过,我希望它被调用!

这是我的字段定义:

[FieldFixedLength(1)]
[FieldTrim(TrimMode.Right)]
[FieldConverter(typeof(AreYouOneOfTheFollowingConverter))]
public KeyValuePair<int, string>? AreYouOneOfTheFollowing;

这是我的转换器([case "":] 永远不会被命中):

public class AreYouOneOfTheFollowingConverter : ConverterBase
{
    public override object StringToField(string from)
    {
        switch (from)
        {
            case "1":
                {
                    return new KeyValuePair<int, string>(1469, "Yes");
                }
            case " ":
                {
                    return new KeyValuePair<int, string>(1470, "No");
                }
            default:
                {
                    if (String.IsNullOrWhiteSpace(from))
                    {
                        return from;
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
        }
    }
}

想法?

最佳答案

ConverterBase 有一个虚拟方法,您可以覆盖它来控制空白的自动处理。

public class AreYouOneOfTheFollowingConverter : ConverterBase
{
    protected override bool CustomNullHandling
    {
        /// you need to tell the converter not 
        /// to handle empty values automatically
        get { return true; } 
    }

    public override object StringToField(string from)
    {
         /// etc...
    }
}

关于c# - 如果值为空格,则不会调用 FileHelpers FieldConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26871984/

相关文章:

c# - 使用 FileHelpers 导入 CSV 文件

c# - 如何删除 FileHelper 中尾随的空行

C# - FileHelper FieldConverter 例程可以引用记录中的其他字段吗?

c# - 为什么禁用延迟加载会导致相关表没有结果?

c# - 配置对我的 SQL Server 的访问

c# - 在 C# 中的循环中捕获变量

java - 有没有一种聪明的方法来使用camel和smooks编写固定长度的平面文件

c# - 为什么在我的新类(class)中创建事件时出现错误?

c# - FileHelpers 在解析大型 csv 文件时抛出 OutOfMemoryException

delphi - 在 Delphi 中读取具有固定长度字段和记录的文本文件