MethodInfo.Invoke方法111 [英] MethodInfo.Invoke Method 111

查看:90
本文介绍了MethodInfo.Invoke方法111的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下问题,我将用较小的方法来简化这些问题,而不是定义我所遇到的整个实际问题.

MathLibrary.dll->>保存在C:\ MyApplications

I have the following problem which Im simplifying in small methods rather than defining the whole real problem I have.

MathLibrary.dll -->> saved at C:\MyApplications

namespace Math
{
     public class SimpleMath
     {
          public int Add(int a, int b)
          {
              return a + b;
          }
     }
}

I want to invoke in another application:

namespace OtherApp
{
     class Program
     {
          static void Main()
          {
               Assembly asm = Assembly.LoadFrom(@"C:\MyApplications\MathLibrary.dll");
               Type simpleMath = asm.GetType("MathLibrary.SimpleMath");
               object obj = Activator.CreateInstance(simpleMath);
               MethodInfo m = simpleMath.GetMethod("Add");
               int sum = m.Invoke(obj,new object[]{10, 20});
          }
     }
}



但是,如果这样定义Add方法,该怎么办:



But what if the Add method was defined as so:

public void Add(int a, int b, out int sum)



如何调用该方法?
谢谢



How could I invoke the method?
Thanks

推荐答案

您可以像其他方法一样通过反射来调用它.除了返回的值将被复制回参数数组之外,以便您可以从调用函数访问它.

例如;

You invoke it like any other method through reflection. except that the returned value will be copied back into the parameter array so you can access it from the calling function.

Eg;

class Program
     {
        delegate int Run(int a, int b, out int sum);
         private static Run invoke;           

          static void Main()
          {
               Assembly asm = Assembly.LoadFrom(@"C:\MyApplications\MathLibrary.dll");
               Type simpleMath = asm.GetType("MathLibrary.SimpleMath");
               object obj = Activator.CreateInstance(simpleMath);
               MethodInfo m = simpleMath.GetMethod("Add");
               invoke = (Run)Delegate.CreateDelegate(typeof(Run), obj, m);
               // call invoke.
               int sum;
               sum = invoke(10, 20, out sum);
          }
     }



或者您可以尝试此



Or you can try this

Assembly asm = Assembly.LoadFrom(@"C:\MyApplications\MathLibrary.dll");
               Type simpleMath = asm.GetType("MathLibrary.SimpleMath");
               object obj = Activator.CreateInstance(simpleMath);
               MethodInfo m = simpleMath.GetMethod("Add");
               int sum;
               sum = m.Invoke(obj,new object[]{10, 20, sum});



如果可以解决您的问题,请投票并标记为解决方案.



Please vote and mark as solution if this solves your problem thanks.


这篇关于MethodInfo.Invoke方法111的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆