lundi 23 mars 2015

Get value from property on generic class using open definition

Is there a way to get the value of a property from an open type using reflection?



class Program
{
static void Main(string[] args)
{
var target = new GenericType<string>();
target.GetMe = "GetThis";
target.DontCare = "Whatever";

var prop = typeof(GenericType<>).GetProperty("GetMe");
var doesntWork = prop.GetValue(target);
}
}

public class GenericType<T>
{
public string GetMe { get; set; }
public T DontCare { get; set; }
}


prop.GetValue(target) throws the following exception:



Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.



I know I can just do target.GetType().GetProperty("GetMe").GetValue(target), but I want to know if there's a way to get the value without knowing the type.


The simple solution would be to have a non-generic base class that just contains GetMe, but I can't make that change right now.






Aucun commentaire:

Enregistrer un commentaire