无需反射即可根据名称动态调用方法的有效方法

时间:2012-12-19 06:26:06

标签: c# reflection delegates

让我试着简化我的问题:

我有四个班级:管理员,用户,玩家,角色

数据库返回我需要执行的方法的名称。例如,如果返回Admins_GetName,则需要在GetName()类上执行Admins方法。 如果返回Players_GetRank,则需要在GetRank()类调用Players方法。

我不想写一个包含我所有业务逻辑的巨大的IF或SWITCH语句。在没有使用反射的情况下,最有效的解决方案是什么?如果可能的话我想避免反射带来的性能损失。

请记住,所有方法可能都有不同的参数,但会返回字符串。

以下是我现在想做的事情: 1)有一个带有switch语句的方法,它将拆分数据库值并找到我需要执行的类和方法。 类似的东西:

switch(DbValue)
{
 case DbValue == "Admins_GetName":
  Declare a delegate to Admins.GetName();
  return;
 case: DbValue = "Players_GetRank"
  Declare a delegate to Players.GetRank();
  return;
  . 
  .
  .
  etc
}

返回类/方法引用;

2)将上面的声明传递给:

var myValue = Retrieved method.invoke()

你们可以建议我用最好的方法来完成这项工作,或者帮助我解决如何实现它的正确语法。

谢谢。

1 个答案:

答案 0 :(得分:4)

需要更多的背景;例如,所有相关方法都有相同的签名吗?在一般的情况下,反射是最合适的工具,只要你没有在紧密的循环中调用它,就可以了。

否则,switch语句方法是合理的,但具有维护开销。如果这有问题,我很想在运行时构建一个委托缓存,例如:

using System;
using System.Collections.Generic;
public class Program
{
    public string Bar { get; set; }

    static void Main()
    {
        var foo = new Foo();
        FooUtils.Execute(foo, "B");
        FooUtils.Execute(foo, "D");
    }
}
static class FooUtils
{
    public static void Execute(Foo foo, string methodName)
    {
        methodCache[methodName](foo);
    }
    static readonly Dictionary<string, Action<Foo>> methodCache;
    static FooUtils()
    {
        methodCache = new Dictionary<string, Action<Foo>>();
        foreach (var method in typeof(Foo).GetMethods())
        {
            if (!method.IsStatic && method.ReturnType == typeof(void)
                && method.GetParameters().Length == 0)
            {
                methodCache.Add(method.Name, (Action<Foo>)
                    Delegate.CreateDelegate(typeof(Action<Foo>), method));
            }
        }
    }
}

public class Foo
{
    public void A() { Console.WriteLine("A"); }
    public void B() { Console.WriteLine("B"); }
    public void C() { Console.WriteLine("C"); }
    public void D() { Console.WriteLine("D"); }
    public string Ignored(int a) { return ""; }
}

使用泛型可以将该方法扩展到多个目标类型:

static class FooUtils
{
    public static void Execute<T>(T target, string methodName)
    {
        MethodCache<T>.Execute(target, methodName);
    }
    static class MethodCache<T>
    {
        public static void Execute(T target, string methodName)
        {
            methodCache[methodName](target);
        }
        static readonly Dictionary<string, Action<T>> methodCache;
        static MethodCache()
        {
            methodCache = new Dictionary<string, Action<T>>();
            foreach (var method in typeof(T).GetMethods())
            {
                if (!method.IsStatic && method.ReturnType == typeof(void)
                    && method.GetParameters().Length == 0)
                {
                    methodCache.Add(method.Name, (Action<T>)
                        Delegate.CreateDelegate(typeof(Action<T>), method));
                }
            }
        }
    }
}
相关问题