Using reflection, call a method of a Field on an object that already exists

前端 未结 1 1425
南旧
南旧 2020-12-20 23:51

I have an instance of a class called AccessData, which inherits from DbContext. So it is an Entity Framework code first context class and looks like this...



        
相关标签:
1条回答
  • 2020-12-21 00:16

    Get the field's value:

    object fldVal = listField.GetValue(accessData);
    

    Get the MethodInfo for the method you want to invoke:

    MethodInfo addMethod = fldVal.GetType().GetMethod("Add", new Type[] { typeof(obj) });
    

    And invoke it:

    addMethod.Invoke(fldVal, new object[] { obj });
    

    Or if you're using .NET 4, you may be able to use the new dynamic keyword to simplify the last 2 steps:

    dynamic fldVal = listField.GetValue(accessData);
    fldVal.Add(obj);
    
    0 讨论(0)
提交回复
热议问题