C#:使用反射动态调用显式实现的方法

标签 c# reflection invoke

我正在尝试使用反射动态调用显式实现的方法。我的方法如下:

public static double GetValueOfAverage(string typeName, string methodName, object[] arguments){
    // ... get the Type for the class
    Type calledType = Type.GetType(typeName, true);

    double avg  = (double)calledType.InvokeMember(
        methodName,
        BindingFlags.InvokeMethod | BindingFlags.Public | 
        BindingFlags.Static | BindingFlags.NonPublic,
        null,
        null,
        new object[] { arguments }
    );

    // Return the value returned by the called method.
    return avg;
}

我调用这个方法如下:

// ... calculate and set the slow moving average value
var slowArguments = new object[] { SlowPeriod, CurrentBar, Input, slowAverage};
movingAvg = GetValueOfAverage("MovingAverage", slowAvgMethod, slowArguments);

而我的移动平均类实现如下:

public static class MovingAverage{
    public static double _EMA(int Period, int CurrentBar, DataSeries Input, DataSeries average){
        double avg = CurrentBar == 0 ? Input[0] : Input[0] * (2.0 / (1 + Period)) + (1 - (2.0 / (1 + Period))) * average[1];
        return avg;
    }
}

我收到以下错误:

无法从程序集“f9e1d550bd4d44ddbdc78abaffa07d31,Version=7.0.1000.22,Culture=neutral,PublicKeyToken=null”加载类型“MovingAverage”。

我已经尝试将命名空间添加到类规范中,但也没有用。我所做的如下:

在 GetValueOfAverage 方法中,我插入了以下代码

var methodInfo = System.Reflection.MethodBase.GetCurrentMethod();
var fullName = methodInfo.DeclaringType.FullName + "." + methodInfo.Name;
string str = methodInfo.DeclaringType.FullName + ".";

行前

Type calledType = Type.GetType(typeName, true);

并替换了行

Type calledType = Type.GetType(typeName, true);

Type calledType = Type.GetType(str+typeName, true);

有人可以帮我理解我做错了什么吗?任何建议和/或意见将不胜感激。谢谢。

最佳答案

对于代码加载类,请尝试指定命名空间,如下例所示:

movingAvg = GetValueOfAverage("ConsoleApplication1.MovingAverage", slowAvgMethod, slowArguments);

如果类型位于当前尚未加载的程序集中,可能仍然不够。 在这种情况下,您可能需要使用程序集限定名称指定类型,如下所示:

movingAvg = GetValueOfAverage("ConsoleApplication1.MovingAverage, ConsoleApplication1", slowAvgMethod, slowArguments);

(第一个 ConsoleApplication1. 是命名空间,第二个 ConsoleApplication1 是程序集名称)

最后,你在通过反射调用方法的代码中犯了一个错误,其中参数作为嵌套对象[]数组传递。 Arguments 参数已经作为 object[] 传递,所以它应该直接传递给 InvokeMember() 方法:

double avg  = (double)calledType.InvokeMember(
               methodName,
               BindingFlags.InvokeMethod | BindingFlags.Public | 
               BindingFlags.Static | BindingFlags.NonPublic,
               null,
               null,
               arguments);

我已经用完整的示例更新了这篇文章,以可视化如何传递类型。 下面的代码编译为ConsoleApplication1.exe

using System;
using System.Reflection;

namespace MyNamespace
{
    public static class MovingAverage
    {
        public static double MyMethod(int Period, int CurrentBar, int[] Input, int[] average)
        {
            return 5;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var arguments = new object[] { 1, 2, new[] { 2 }, new[] { 4 } };

            Console.WriteLine(GetValueOfAverage("MyNamespace.MovingAverage", "MyMethod", arguments)); //if assembly is already loaded
            Console.WriteLine(GetValueOfAverage("MyNamespace.MovingAverage, ConsoleApplication1", "MyMethod", arguments)); //if assembly is not loaded yet
            Console.WriteLine(GetValueOfAverage(typeof(MovingAverage), "MyMethod", arguments)); //known type
            Console.ReadKey();
        }

        public static double GetValueOfAverage(string typeName, string methodName, object[] arguments)
        {
            // ... get the Type for the class
            Type calledType = Type.GetType(typeName, true);
            return GetValueOfAverage(calledType, methodName, arguments);
        }

        public static double GetValueOfAverage(Type calledType, string methodName, object[] arguments)
        {
            double avg = (double)calledType.InvokeMember(
                           methodName,
                           BindingFlags.InvokeMethod | BindingFlags.Public |
                           BindingFlags.Static | BindingFlags.NonPublic,
                           null,
                           null,
                           arguments);

            // Return the value returned by the called method.
            return avg;
        }
    }
}

关于C#:使用反射动态调用显式实现的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24829128/

相关文章:

c# - Xamarin.iOS 中的文件选择器

基于对象类型的 Java getter 返回类型

ruby-on-rails - 如何在 Rails 中动态调用或调用类?

.net - 点网反射: Calling Invoke on MethodInfo With 'out' Parameter from F#

ios - 为什么 numberOfRowsInSections : method is invoked 5 times ? 和 numberOfSections 6 倍?

c# - 一起使用 npgsql 12 和 ef 6 - 有人成功了吗?

c# - 分配 Action<T> 方法和订阅 Action<T> 事件之间的区别

c# - 我对 IsLoaded 的理解是否正确?

perl - 确定Perl代码引用的子例程名称

不使用反射的 C# 字符串到对象