【发布时间】:2020-09-13 14:26:22
【问题描述】:
我的主程序正在通过另一个类读取电子表格,该类对电子表格的架构(即其中的数据类型)一无所知。我的方法是定义一个定义这些数据类型的电子表格记录,并将该记录作为一个类或结构传递给被调用的类以执行此电子表格读取。
问题是 C# 编译器抱怨它不能将 main 的 SpreadsheetRecord 数据类型隐式转换为被调用类已知的数据类型。当然不能,因为目标类对此数据类型一无所知。那么应该如何将电子表格的模式传递给负责读取和保存电子表格数据的类例程呢?
void class Main
{
public class SpreadsheetRecord
{
public double volAvg;
public double volOvr10;
public double sumScore;
}
static string[] sheetHeads = { "Volume (10 Day Avg)", "Volume (Today/Avg 10 Day)",
"Equity Summary Score from StarMine from Refinitiv" };
SpreadsheetData sheetDat = new SpreadsheetData(new SpreadsheetRecord(), sheetHeads);
...
}
public class SpreadsheetData //SpreadsheetData parses an "unknown" spreadsheet.xls file
{
public Dictionary<string, Record> SheetDB { get; private set; } //declaration of database
public class Record { }; //schema for incoming spreadsheet data record
public SpreadsheetData(Record schemaRecord, string[] recordHeadings) //constructor read in spreadsheet
{
...
using (IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(sheetInputFile.OpenRead()))
{...
FieldInfo[] recordFieldInfo = typeof(Record).GetFields();
for (int i = 1; i < result.Tables[0].Rows.Count; i++)
{
for (int j = 0; j < recordHeadings.Length; j++)
recordFieldInfo[j].SetValue(schemaRecord, sheet1.Rows[i][Column2RecordCrossIndx[j]]);
SheetDB.Add(sheet1.Rows[i][indxOfSymbol].ToString(), schemaRecord); //store sheet data record
}
...
}
}
}
【问题讨论】:
-
我认为使该类成为通用类并传递记录的类型(SpreadsheetRecord)应该可以。
public class SpreadsheetData<T> where T : class
标签: c# class reflection parameter-passing generic-programming