我的主程序正在通过另一个类读取电子表格,该类对电子表格的架构(即其中的数据类型)一无所知。我的方法是定义一个定义这些数据类型的电子表格记录,并将该记录作为类或结构传递给被调用的类,以读取电子表格。
问题在于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
}
...
}
}
}
答案 0 :(得分:0)
好吧,采用通用类似乎可以使电子表格读取类获得未知的数据类型(即数据库记录)。谢谢你欢迎其他任何建议。
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<SpreadsheetRecord> sheetDat = new SpreadsheetData<SpreadsheetRecord>(sheetHeads);
...
}
public class SpreadsheetData<T> where T : new() //SpreadsheetData parses an "unknown" spreadsheet.xls file
{
public Dictionary<string,T> SheetDB { get; private set; } //allow read access to database
public SpreadsheetData<T>(string[] recordHeadings) //constructor to read in spreadsheet
{
...
using (IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(sheetInputFile.OpenRead()))
{...
SheetDB = new Dictionary<string,T>(sheet1.Rows.Count); //create database instance
T schemaRecord = new T(); //create database record instance
FieldInfo[] recordFieldInfo = typeof(T).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
}
...
}
}
}