需要更多的上下文;例如,是否所有有问题的方法都具有相同的签名?在一般情况下,反射是最合适的工具,只要你不在一个紧密的循环中调用它,就可以了。
否则,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));
}
}
}
}
}