简体   繁体   中英

Passing unknown type as parameter to a method then casting to that type later on

I need to create a method that accepts an unknown type and then later uses that type to access an object.

A little more detail. I have a DevEx grid and I'm using GetRow to get a record. GetRow must be of the type of Linq class object to access the properties of the record. I'm trying to create a generic method that will allow me to pass in the type of Linq object and then dynamically cast the result from GetRow to that object. I will then get the column fieldname to access the properties like so (objectType is the unknown type):

void DoGrid (GridView gv, objectType)
{    

    PropertyInfo[] properties = objectType.GetProperties();

    foreach (GridColumn col in gv.Columns)
        {
             if (col.Visible)
             {
                 PropertyInfo property = properties.Where(prop => prop.Name == col.FieldName).FirstOrDefault();
                 ...
             }
        }

}

Are you just looking for a way to do this with generics? Perhaps something like:

void DoGrid<T>(GridView gv)
{
    PropertyInfo[] properties = typeof(T).GetProperties();

    foreach (GridColumn col in gv.Columns)
    {
        ...
    }
}

and then you'd use it like:

DoGrid<MyClassFullOfProperties>(myGridView);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM