使用反射,调用现场的方法已经存在的对象上反射、对象、存在、现场

由网友(恍一眼得一心)分享简介:我有一类称为AccessData,它继承的DbContext的一个实例。因此,它是一个实体框架code第一上下文类,看起来像这样... I have an instance of a class called AccessData, which inherits from DbContext. So it is a...

我有一类称为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);
阅读全文

相关推荐

最新文章