mardi 26 mai 2020

Passing an unknown datatype parameter in C#

My main program is reading a spreadsheet via another class, which knows nothing about the schema of (i.e. data types within) the spreadsheet. My approach is to define a spreadsheetRecord that defines these data types and pass that record as either a class or struct into the class being called to do this spreadsheet read.

The problem is the C# compiler gripes it can't implicitly convert main's SpreadsheetRecord datatype with the one known to the class being called. Of course it can't because the destination class knows nothing about this datatype. So how should the schema for the spreadsheet be passed to the class routine that's responsible for reading and saving the spreadsheet data?

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
            }
            ...
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire