jeudi 2 juillet 2015

InvokeMember on generic class results in an exception

I have the following classes

public class RowDef
{
    string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public RowDef()
    {

    }
    public RowDef(string name)
        : this()
    {
        Name = name;
    }
}

public class RowDef<T> : RowDef
{

    public RowDef()
    {
    }

    public RowDef(string name)
        : base(name)
    {

    }

    T _value;
    public T Value
    {
        get { return _value; }
        set { _value = value;}
    }
}

I am trying to use reflection to get the value of the "Value" property like this

List<RowDef> rows = new List<RowDef>() { new RowDef<int>() { Value = 5 }, new RowDef<float>() { Value = 5.0f }, new RowDef<string>() { Value = "XXXX" } };
foreach (var row in rows)
{
  var v = typeof(RowDef<>).InvokeMember("Value", BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic |
                            BindingFlags.Instance | BindingFlags.GetProperty, null, child, null);
}

But I get the following exception

A first chance exception of type 'System.InvalidOperationException' occurred in mscorlib.dll Additional information: Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.

what can I do to fix the problem?





Aucun commentaire:

Enregistrer un commentaire