Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

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

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
}

Using Reflections, I have identified one of these DbSet properties on the AccessData object like this...

var listField = accessData.GetType().GetField(typeName + "List");

I now need to be able to add objects to this DbSet property.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...