문제

How to get this to work?

GSD a class that is used to store cache images of SQL tables. GSD has several public static properties representing different "CacheTables", which are Dictionary=long,rowtypeclass= objects, each with a different rowtype class. The rowtype class objects model SQL table rows.

public class GSDataObject
{
    private Dictionary<long, GRPListRow> prvGRPList;
    private Dictionary<long, TestTableRow> prvTestTable;
    //=======================================
    public Dictionary<long, GRPListRow> GRPList
    {
        get { return prvGRPList;}
        set { prvGRPList = value; }
    }

    //=====================================
    public Dictionary<long, TestTableRow> TestTable
    {
        get { return prvTestTable; }
        set { prvTestTable = value; }
    }


public class TestTableRow{

        public int ID  { get; set; }
        public string Field1  { get; set; }
        public string Field2  { get; set; }
        public string Field3  { get; set; }
        public string Field4  { get; set; }
        public string Field5  { get; set; }
        public string Field6  { get; set; }
        public string Field7  { get; set; }
        public string Field8  { get; set; }
}

GSD and its different CacheTable properties work fine when declared hard-coded; I want to access them with reflection.

Specifically, I want to get a particular Row from a particular CacheTable in an instance of GSD, update that row, and then put it back. The instructions below describe the "get the row" phase.

The first three instructions work, and the resulting wrkCacheTableObject is of the correct type Dictionary=long,wrkRowtype=. However, wrkCacheTableObject is not indexed, so I can't retrieve rows from it.

wrkGSD is an instantiation of a class GSD. wrkCacheTableName is a string name of the particular CacheTable property. wrkRowType is the string class name of the row type.

wrkRow = Activator.CreateInstance(wrkRowType);
PropertyInfo wrkTablePropInfo = wrkGSDOType.GetProperty(wrkCacheTableName);

object wrkCacheTableObject = wrkTablePropInfo.GetValue(wrkGSD, null);  // <== gives correct CacheTable instance
wrkTableDictObject = (Dictionary<long, object>)wrkCacheTableObject;  //<=== fails here

wrkRow = wrkTableDictObject[wrkRowID];

// update wrkRow fields using reflection //<== this works if I retrieve wrkRow via hard code
// put it back into wrkTableDictObject
// put wrkTableDictObject back into wrkGSD

I'm not fixed on this particular set of instructions. And maybe if I can get the first phase above to work, it will show me how to do the other phases.

도움이 되었습니까?

해결책

Found the answer via Experts Exchange:

dynamic wrkCacheTableObject = wrkTablePropInfo.GetValue(wrkGSD, null);
//--- get the row using dynamic
dynamic wrkRow = wrkCacheTableObject[(long)varAJR.rowID];
//--- put the row back
wrkCacheTableObject[(long)varAJR.rowID]= wrkRow;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top