简体   繁体   中英

declare a generic using Type class (C#)

I'm trying to cast from the object to List , where I know the 'T' at runtime. Is there is any way to cast or any other solution to it

//This return an object by default ,but in runtime returning List<T>

var getList = modelClass.GetValue(modelObject);

Now , getList is not allowing to use Linq properties coz of this.

I know the Type (T) (getting dynamically through code)

Is there any work around to cast this like :

var getList = (List<typeClassObject>))modelClass.GetValue(modelObject);

Kindly please help on this

Assuming that modelClass.GetValue(modelObject) returns and IEnumerable<someType> , you should be able to do the transformation as follows:

var getList = modelClass.GetValue(modelObject)
                 .Select(obj => ((object) obj) as typeClassObject);

getList is now an IEnumerable<typeClassObject>

Doing:

var getList = modelClass.GetValue(modelObject)
                 .Select(obj => ((object) obj) as typeClassObject)
                 .ToList();

would have getList being List<typeClassObject>

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