简体   繁体   中英

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?

As the error is trying to tell you, it doesn't make sense to to use RowDef<> directly. RowDef<> isn't really a type; it's a type constructor that can be used to make concrete types like RowDef<string> .

In your particular example, you actually just want row.GetType() , which will return the concrete RowDef<T> type of that instance.

Or, better yet, don't use Reflection at all, and instead add an abstract object UntypedValue property to the base class and use that.

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