我有这样做的代码:
var engine = new FileHelperEngine<SampleType>();
var records = engine.ReadString("asdf|fdsa");
var showString = records[0].Field1 + records[0].Field2;
SampleType 类如下所示:
[DelimitedRecord("|")]
public class SampleType
{
public string Field2;
public string Field1;
}
结果集如下:
records[0].Field1
的值为 fdsa
records[0].Field2
的值为 asdf
如果我运行 ReSharper 清理,它将按字母顺序对变量进行排序。 SampleType 类将如下所示:
[DelimitedRecord("|")]
public class SampleType
{
public string Field1;
public string Field2;
}
但是现在我的程序逻辑已经改变了。
records[0].Field1
的值为 asdf
records[0].Field2
的值为 fdsa
有没有办法告诉类定义变量的顺序无关紧要?变量的定义顺序突然变得相关,这与我见过的任何其他类相反,我觉得非常令人不安和奇怪。
最佳答案
我不完全确定,但我认为您想要一种方法让 FileHelpers 使用字段的明确指定的顺序,而不是隐式的“它们在来源'。
如果我是对的,你想要the FieldOrder
attribute来自 FileHelpers 库:
Force field order with [FieldOrder] attribute:
//-> You first declare a Record Mapping class: Input.txt 10248|VINET|04071996|32.38 10249|TOMSP|05071996|11.61 10250|HANAS|08071996|65.83 10251|VICTE|08071996|41.34 RecordClass.cs [DelimitedRecord("|")] public class Orders { [FieldOrder(20)] public string CustomerID; [FieldConverter(ConverterKind.Date, "ddMMyyyy")] [FieldOrder(30)] public DateTime OrderDate; [FieldConverter(ConverterKind.Decimal, ".")] // The decimal separator is "." [FieldOrder(40)] public decimal Freight; [FieldOrder(10)] public int OrderID; }
关于你的评论
However I am quite surprised of how OK this way of solving a problem in such a library seems to you. And for the record, this is not logical, and to be able to understand it, you'll have to "overthink" :p It's not a part of the languages design
你是对的,这里 FileHelper 的默认操作模式(使用字段的源顺序作为它们的记录顺序)不是“ native ”C#,而且确实不是特别的“C#- ish'做事的方式;但是如果 FileHelpers 的作者和用户想要它,那也没关系。它确实具有更动态语言风格的风格,但那是 一点无论如何 C# 的发展方向...
关于c# - FileHelper 无法处理其类中的 ReSharper 排序变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39368660/