我想读取并最终将它们存储在数据库表中的制表符分隔值(TSV)文本文件中有数据。对于TSV文件,每一行包含一个记录,但是在一个文件中该记录可以包含2个字段,在另一个文件中可以包含4个字段,依此类推。我编写了工作代码来处理2个字段的记录,但是我认为这可能是一个不错的选择通用方法(或两个)的情况,而不是为每种记录编写新方法。但是,由于两个问题,我无法对此进行编码:我无法创建用于保存记录数据的新对象,并且我不知道如何使用反射来一般地填充对象的实例变量。 >
我看过其他几篇类似的文章,包括Datatable to object by using reflection and linq
下面是有效的代码(如果重要的话,这是在Windows中,也是无效的代码。
public class TSVFile { public class TSVRec { public string item1; public string item2; } private string fileName = ""; public TSVFile(string _fileName) { fileName = _fileName; } public TSVRec GetTSVRec(string Line) { TSVRec rec = new TSVRec(); try { string[] fields = Line.Split(new char[1] { '\t' }); rec.item1 = fields[0]; rec.item2 = fields[1]; } catch (Exception ex) { System.Windows.Forms.MessageBox.Show("Bad import data on line: " + Line + "\n" + ex.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } return rec; } public List<TSVRec> ImportTSVRec() { List<TSVRec> loadedData = new List<TSVRec>(); using (StreamReader sr = File.OpenText(fileName)) { string Line = null; while ((Line = sr.ReadLine()) != null) { loadedData.Add(GetTSVRec(Line)); } } return loadedData; } // *** Attempted generic methods *** public T GetRec<T>(string Line) { T rec = new T(); // compile error! Type t = typeof(T); FieldInfo[] instanceVars = t.GetFields(); string[] fields = Line.Split(new char[1] { '\t' }); for (int i = 0; i < instanceVars.Length - 1; i++) { rec. ??? = fields[i]; // how do I finish this line??? } return rec; } public List<T> Import<T>(Type t) { List<T> loadedData = new List<T>(); using (StreamReader sr = File.OpenText(fileName)) { string Line = null; while ((Line = sr.ReadLine()) != null) { loadedData.Add(GetRec<T>(Line)); } } return loadedData; } }
我看到了线T rec = new T();在上述文章中,但对我不起作用...
如果可能,我将对如何进行这项工作提出任何建议。我想了解有关将反射与泛型一起使用的更多信息,所以我不仅想了解如何,而且还想了解原因。
我想读取并最终将它们存储在数据库表中的制表符分隔值(TSV)文本文件中有数据。对于TSV文件,每一行包含一个记录,但是在一个文件中,记录可以...
我希望@EdPlunkett将他的建议发布为答案,而不是发表评论,所以我可以将其标记为答案...