本文介绍了现有实例上的C#反射InvokeMember的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

我有点卡在这里,有一些要求.我们有一个适用于不同客户的应用程序的基本代码,其中一些具有仅适用于他们的特定代码,我们正在寻找一种将基本代码合并到一个应用程序中并在不同程序集中对特定操作进行编码的方法.

我的方法是将大多数方法虚拟化,当某人需要在方法中添加特定操作时,他应该继承基类,重写该方法并更改在那里所需的内容.之后,在代码库中,它将加载程序集并查找哪些方法被覆盖,以便当说Start()方法执行时,如果该方法被覆盖,则应从程序集中获取该方法,然后调用InvokeMember,但目标应该是该类的实际实例.
这么说吧,我有一个像这样的方法:

Hi everyone

I''m kinda stuck here with some requirement. We have a base code for an app that works for different clients, out of which some have specific code that applies just to them and we were looking for a way to merge the base code into one app and code the specific operations in different assemblies.

My approach is to make most of the methods virtual and when someone needs to add a specific operation in a method, he should inherit the base class, override the method and change whatever he has to there; after that, on the code base, it will load the assembly and find which methods were overridden so that when the method let''s say Start() executes, if it''s overridden, it should get the method from the assembly and call the InvokeMember but the target should be the actual instance of the class.
SO let´s say that I have a method like this:

//Class in basecode
public class ProcessManager
{
     public virtual void Start()
     {
      //Check to see if the method is overridden
      //If it is, load the assembly:
      Assembly myDll = Assembly.LoadFrom(@"C:\Users...\My.dll");
            Type myType = myDll.GetType("MyNameSpace.OverridenClass");
            MethodInfo mi = myType.GetMethod("Start");
            myType.InvokeMember(mi.Name, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, this, null);
     }
}
//Class in a different Assembly
public class OverriddenClass : ProcessManager
{
     public override Start()
     {
        //My implementation
     }
}



这样,我得到了TargetException,对象与目标不匹配.如果重写的类继承自ProcessManager,则这就是为什么.
有没有办法纠正这个问题,或者这种方法不正确?我不想指定新实例,因为ProcessManager实例已经完成了一些初始化并具有一些值,所以我需要在该实例上执行该方法.

你们推荐什么???

非常感谢!



Like that, I''m getting a TargetException, the object doesn''t match target. Idk why, if the overriden class inherits from ProcessManager.
Is there a way to correct this or is this approach incorrect?? I don''t wanna specify a new Instance since the ProcessManager instance has already done some Initialization and has some values so I need to execute that method on that instance.

What do you guys recommend????

Thanks a lot!

推荐答案


这篇关于现有实例上的C#反射InvokeMember的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 01:12