使用反射,调用现场的方法已经存在的对象上 [英] Using reflection, call a method of a Field on an object that already exists
问题描述
我有一类称为AccessData,它继承的DbContext的一个实例。因此,它是一个实体框架code第一上下文类,看起来像这样...
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...
public class AccessData : DbContext
{
public DbSet<apps_Apps> apps_AppsList;
public DbSet<apps_AppsOld> apps_AppsOldList;
...
//Several other DbSet<> properties
}
使用的反思,我已经确定了AccessData对象,像这样...
Using Reflections, I have identified one of these DbSet properties on the AccessData object like this...
var listField = accessData.GetType().GetField(typeName + "List");
我现在需要能够将对象添加到这个DbSet属性
I now need to be able to add objects to this DbSet property.
由于我只是有重新presents的DbSet场,我怎么把这个特定字段的添加方法AccessData物体上,并传递一个对象?一个字段信息对象
Given that I only have a FieldInfo object that represents the DbSet field, how do I call the Add method of this particular Field on the AccessData object and pass in an object?
或者换句话说,我怎么叫下面的?
Or in other words how do I call the following?
accessData.<FieldInfoType>.Add(obj);
希望这是有道理的。
Hope this makes sense.
推荐答案
获取字段的值:
object fldVal = listField.GetValue(accessData);
获得的MethodInfo
为要调用的方法:
MethodInfo addMethod = fldVal.GetType().GetMethod("Add", new Type[] { typeof(obj) });
和调用它:
addMethod.Invoke(fldVal, new object[] { obj });
或者,如果您使用的是.NET 4中,您可以使用新的动态
关键字来简化最后2步:
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);
这篇关于使用反射,调用现场的方法已经存在的对象上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!