我正在尝试使用 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/