我有一些用逗号分隔的文本文件,我想读取一行,然后实例化它并为属性赋值。文本文件的数量将在未来增长,但现在,我只需要处理其中的少数文件。
因此,我创建了一个接受FileInfo参数的基类,但问题是如何为实例分配值?在基类中,它将不知道属性名是什么。我认为我应该迭代这些属性并根据索引分配它们,但是t.GetType().GetProperties()不返回任何项。
public class AccountDataFile : DataFileBase<AccountDataFile.Account>
{
public class Account
{
public string Name;
public string Type;
}
public AccountDataFile(FileInfo fiDataFile) : base(fiDataFile) { }
}基类:
public class DataFileBase<T> where T : new()
{
public List<T> Data;
public DataFileBase(FileInfo fi)
{
this.Data = new List<T>();
var lines = fi.ReadLines();
foreach (var line in lines)
{
var tokens = line.Split(CONSTS.DELIMITER);
var t = new T();
// how to assign values to properties?
this.Data.Add(t);
}
}
}发布于 2014-05-12 16:30:02
使继承类提供实现:
public abstract class DataFileBase<T>
{
protected abstract T BuildInstance(string[] tokens);
}
public AccountDataFile : DataFileBase<AccountDataFile.Account>
{
protected override Account BuildInstance(string[] tokens)
{
var account = new Account();
account.Name = tokens[0]; // or whatever
return account;
}
}发布于 2014-05-12 16:31:47
您可以向基类添加一个抽象方法,以创建正确的对象类型。在DataFileBase中添加如下方法:
public abstract T CreateObject();并在AccountDataFile中实现:
public override AccountDataFile.Account CreateObject() { new AccountDataFile.Account(); }发布于 2014-05-12 16:39:51
考虑一下现有的CSV解析器/ C#读取器?。
如果您仍然希望获得您自己的-许多序列化程序使用属性对字段名/列匹配执行属性。例如,在运行时用ColumnAttribute或类似的自定义属性值和读取值注释您的ColumnAttribute类型。MSDN有一篇涵盖阅读属性的文章使用反射访问属性。
// starting point to read attributes:
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(myType); https://stackoverflow.com/questions/23614159
复制相似问题