[英]Passing an unknown datatype parameter in C#
我的主程序是通過另一個 class 讀取電子表格,它對電子表格的架構(即其中的數據類型)一無所知。 我的方法是定義一個定義這些數據類型的電子表格記錄,並將該記錄作為 class 或結構傳遞到被調用的 class 以執行此電子表格讀取。
問題是 C# 編譯器抱怨它不能將 main 的 SpreadsheetRecord 數據類型隱式轉換為 class 已知的數據類型。 當然不能,因為目標 class 對此數據類型一無所知。 那么應該如何將電子表格的模式傳遞給負責讀取和保存電子表格數據的 class 例程呢?
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
}
...
}
}
}
好吧,使用通用 class 似乎可以將未知數據類型(即數據庫記錄)放入讀取 class 的電子表格中。 謝謝一堆。 歡迎任何其他建議。
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
}
...
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.