samedi 7 septembre 2019

Reflection Getting getting List in .net core 2.2

Consider the following (null checks and validation have been taken out to shorten the code):

var type = requestModel.GetType();
var properties = new List<PropertyInfo>(type.GetProperties());
var listProperty = properties.FirstOrDefault(x => x.Name.Equals(_listName));
var castedListProperty = (IList) listProperty.GetValue(properties);

The codd crashes on the 4th line. The error is:

System.Reflection.TargetException: 'Object does not match target type.'

if I inspect the type of listProperty I get the following:

{System.Collections.Generic.IList`1[MyProj.Model.Book] Books}

if I inspect the properties variable, it is a list and in its first value is an object of same type as above.

I'm really not sure where I went wrong here.





Aucun commentaire:

Enregistrer un commentaire