从设计的角度来看,我认为你的做法是错误的。虽然您可能能够一起破解一些东西来解决您的构造函数问题,但您正在尝试将Box 类用于两种不兼容的用途。相反,您应该有两个单独的类。
FileHelpers 是一个用于描述 csv 文件的库,以便您可以轻松地导入它们。你应该有一个BoxFileSpec 来描述你的文件。它真的不是一个合适的 C# 类——它可能有: 表示未使用列的虚拟字段;很多属性[FieldNullValue],[FieldQuoted],[FieldConverter];等等。它最适用于公共字段(不是 C# 最佳实践的 FileHelpers 限制)等。它是描述导入文件的 方便 语法。它应该不包含任何逻辑或特殊构造函数。
然后你可以有一个干净的最佳实践Box 类,它有你专门的构造函数和额外的逻辑、属性、方法等等。
然后您使用FileHelperEngine<BoxFileSpec> 将记录读入数组并将其映射到Box 的可枚举(通过Linq 或AutoMapper 之类的库)。
类似:
/// A 'real' class. Add methods, getters, setters, whatever.
/// FileHelpers doesn't use this class.
class Box
{
public int Width { get; set; }
public int Height { get; set; }
public int Length { get; set; }
public Box(int width, int height, int length)
{
this.Width = width;
this.Height = height;
this.Length = length;
}
}
/// A 'real' class. Add methods, getters, setters, whatever.
/// FileHelpers doesn't use this class.
class ProductBox : Box
{
public ProductBox(int width, int height, int length)
: base(width, height, length)
{ }
public int Name { get; set; }
}
/// This is the class FileHelpers will use
/// This class describes the CSV file only. Stick to whatever
/// syntax conventions are required by FileHelpers.
[DelimitedRecord(";")]
class ProductBoxFileSpec
{
[FieldQuoted(QuoteMode.OptionalForRead)]
public int Width;
[FieldQuoted(QuoteMode.OptionalForRead)]
public int Height;
[FieldQuoted(QuoteMode.OptionalForRead)]
// Handle non-US formats such as , decimal points
// convert from inches to centimetres?
// you get the idea...
[FieldConverter(MyCustomizedLengthConverter)]
public int Length;
[FieldOptional]
public string SomeDummyExtraCSVColumn;
}
class Program
{
static void Main(string[] args)
{
var engine = new FileHelperEngine<ProductBoxFileSpec>();
var productBoxRecords = engine.ReadFile(filePath);
var productBoxes = productBoxRecords
.Select(x => new ProductBox(x.Width, x.Height, x.Length) { Name = x.Name });
}
}