我想要一个可以存储在变量中以供以后使用的委托,该变量具有自定义数量的自定义参数。我的意思是,我想为其提供具有不同返回类型和不同参数的不同方法。例如:
public double Sum (double a, double b) {return a + b;}
public char GetFirst (string a) {return a[0];}
public bool canFlipTable (object[] thingsOnIt) {return thingsOnIt.Length <= 3;}
DoTheThing<double> thing1 = new DoTheThing<double>(Sum);
DoTheThing<char> thing2 = new DoTheThing<char>(GetFirst);
DoTheThing<bool> thing3 = new DoTheThing<bool>(canFlipTable);
thing1.Call(10.3, 5.6); //15.9
thing2.Call("Hello World"); //'H'
thing3.Call(new object[] {new Lamp(), new Laptop(), new CoffeMug()}); //true
我已经弄清楚了返回值和调用方法,但我在存储方法时遇到问题
如果我使用“public DoTheThing(Action method)”,它会说参数不匹配
我什至尝试使用以“params object[] p”作为参数的委托,但它也不起作用
编辑:
我忘了告诉,该方法将始终有一个返回类型和至少 1 个参数
编辑2:
我的目标是创建一个包装类,它缓存非常昂贵的方法的输出,如果再次调用相同的东西,它会返回缓存的值。
当然,我可以使用接口来解决这个问题,但我想用不能简单编辑的类来解决这个问题,并且我也想让这个变得灵活,所以将缓存放在我调用该方法的同一位置并不是一个好主意。选项之一。
到目前为止我的代码:
public class DoTheThing <T>
{
public delegate T Method(params object[] parameters);
Func<T> method;
ParameterInfo[] pInfo;
public DoTheThing (Method method)
{
this.method = method;
Type type = typeof(Method);
MethodInfo info = type.GetMethod ("Invoke");
if (info.ReturnType != typeof(T)) {
throw new Exception ("Type of DoTheThing and method don't match");
}
pInfo = info.GetParameters ();
}
public T Call (params object[] parameters) {
if (parameters.Length != pInfo.Length) {
throw new Exception ("Wrong number of arguments, " + parameters.Length + " instead of " + pInfo.Length);
return default(T);
}
for (int i = 0; i < parameters.Length; i++) {
if (pInfo[i].ParameterType != parameters[i].GetType()) {
throw new Exception ("Wrong parameter: " + parameters [i].GetType () + " instead of " + pInfo [i].ParameterType + " at position: " + i);
return default(T);
}
}
return (T)method.DynamicInvoke (parameters);
}
}