c# - 在运行时指定通用委托(delegate)类型参数

标签 c# generics delegates

在设置之后,我有几个通用函数,我需要在运行时选择由两个字符串标识的类型和函数。

我的第一次尝试是这样的:

public static class FOOBAR
{
    public delegate void MyDelegateType(int param);

    public static void foo<T>(int param){...}
    public static void bar<T>(int param){...}

    public static void someMethod(string methodstr, string typestr)
    {
        MyDelegateType mydel;
        Type mytype;
        switch(typestr)
        {
            case "int": mytype = typeof(int); 
                        break;
            case "double": mytype = typeof(double); 
                           break;
            default: throw new InvalidTypeException(typestr);
        }
        switch(methodstr)
        {
            case "foo": mydel = foo<mytype>; //error
                        break;
            case "bar": mydel = bar<mytype>; //error
                        break;
            default: throw new InvalidTypeException(methodstr);
        }
        for(int i=0; i<1000; ++i)
            mydel(i);
    }
}

由于这不起作用,我嵌套了这些开关(在 typestr 开关内嵌套了一个 methodstr 开关,反之亦然),但该解决方案非常丑陋且无法维护。

类型的数量几乎是固定的,但是像 foobar 这样的函数数量会增加很多,所以我不想要嵌套开关。

那么我怎样才能在不使用嵌套开关的情况下使它工作呢?

最佳答案

你需要使用反射:

MethodInfo method = typeof(FooBar).GetMethod(methodStr, BindingFlags.Static);
Type genericParam = Type.Parse(typestr);

MethodInfo genericMethod = method.MakeGenericMethod(genericParam);

for(int i=0; i<1000; ++i)
    genericMethod.Invoke(null, new object[] { i });

如果方法的(非泛型)签名始终相同,则创建委托(delegate)会更快,如下所示:

Action<int> del = Delegate.CreateDelegate(typeof(Action<int>), null, genericMethod);

for(int i=0; i<1000; ++i)
    del(i);

关于c# - 在运行时指定通用委托(delegate)类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2826680/

相关文章:

C# Winforms 应用挂起而不是抛出异常

c# - 为什么枚举不使用 protobufs 反序列化?

c# - 如何在 .NET 库中使用单例模式的 ILogger 抽象?

c# - 原始 ssh 连接(低级)

c# - 迭代 T[] 转换为 IList<T> 的开销

proxy - 如何使用 dart 实现委托(delegate)/代理?

java - 从 Java 中的字段中提取多个泛型类型

c# - 如何转换实现接口(interface)的具体类的列表

asp.net - ASP.NET 中的自定义事件

java - 从 Java 中的两个方法抽象代码,也许使用委托(delegate)?