vendredi 16 avril 2021

casting object to list of interface from a propertyinfo getvalue [duplicate]

interface blah 
{ 
  int status;
}
class B : blah
{
  public int status;
}
class A : blah 
{
  public int status;
  public List<B> items;
}

var the_a = new A() { items = new List<B>() { new B() { status = 5; } } };

// this gets passed around and eventually gets to a generic function
// that is trying to update status on the item and any children that might also have the interface blah

PropertyInfo pinfo = null; /* the PropertyInfo of items on class A */

// this function

private function update<T>(T data) where T : blah
{

 if (pinfo.PropertyType.IsGenericType && pinfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
 {
     // i now know my generic has a list, and that the list is of type List<blah>
     // however .net standard 2.0 doesn't allow casting as IList;
     // you have to pass a type
     // however it also wont allow cast to IList<blah>
     // how do a get either IList<blah> or even a list of objects
     // something i can loop through?
     var temp_object = pinfo.GetValue(data);
     // how does one iterate or cast this to a iterable list of interface blah?
 }
}



I need to edit the data of an interface on a property of a generic. The above code should show what im after, not exactly how i got to that point though. This question doesnt seem to answer it. C# casting the result of GetValue from PropertyInfo to a generic list





Aucun commentaire:

Enregistrer un commentaire