如何在运行时初始化一个包含工件的所有静态类的列表,以便能够动态地调用它们的方法和它们的参数?



我有以下问题:我需要测试一个算法列表(~300)的最大速度性能。

由于每一个都是唯一的,所以我将它们创建为静态类,并创建一个execute()函数,如下所示。

每一个都有一些固定的参数(数量相同),最终我可以将它们作为const;

我能够得到一个execute()方法的列表,创建一个委托并运行它。

现在在C中,我将创建一些函数指针,就是这样。

创建函数指针数组

我如何获得一个委托给整个静态对象,而不仅仅是特定的方法?

实际上我需要一个它们的列表或数组

我更喜欢在initialization()中做一些繁重的工作,比如反射,所以我可以有max。

execute();

现在我不确定这是最好的方法,我不是c#专家。

谢谢你的建议。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace test
{
public static class algorithms
{
public static void initialize()
{
List<Type> types = typeof(algorithms).GetNestedTypes(BindingFlags.Public | BindingFlags.Static).ToList();
foreach ( Type t in types )
{
var method = t.GetMethod("Execute");
var execute = (Func<int, int>)Delegate.CreateDelegate(typeof(Func<int, int>), null, method);
int reply = execute(0x12345678); // I was able to obtain *ptr to execute() for each one
// how can I obtain a *ptr to entire object in order to access it's members too ?
}
}
// list of ~300 algorithms, unique (so no need to have instances)
public static class alg1
{
public static string Name;      // each share the same parameters
public static string Alias;
public static int Execute(int data)     // the same execute function
{
// but different processing for each algorithm
return 1;
}
}
public static class alg2
{
public static string Name;
public static string Alias;
public static int Execute(int data)
{
return 2;
}
}
public static class alg3
{
public static string Name;
public static string Alias;
public static int Execute(int data)
{
return 3;
}
}
}
}

现在在C中,我会做一些函数指针,就是这样。创建一个函数指针数组

在c#中,List<Func<int,int>>是你想要的。

我如何获得一个委托到整个静态对象,而不仅仅是特定的方法?实际上我需要它们的一个列表或数组

就是List<Type>。静态类永远不会有"对象"。只有一个类型。

另一种更自然的c#建模方法是使每个算法都是非静态类型,然后你可以让它们都继承一个基类或接口,例如:
public abstract class Algorithm
{
public static string Name;      // each share the same parameters
public static string Alias;
public abstract int Execute(int data);
}
public class alg1 : Algorithm
{
public override int Execute(int data)     // the same execute function
{
// but different processing for each algorithm
return 1;
}
}

然后使用List<Algorithm>,可以写像

这样的东西
foreach (var a in algorithms)
{
var result = a.Execute(3);
}

最新更新