重播function和参数列表

我有一系列function,我想拥有以下function。

  • 调用该函数时,将其自身添加到记住参数和值的函数列表中
  • 允许在以后调用函数列表

不同的function有各种不同的参数,我很难想到一个优雅的方法来做到这一点。 任何帮助,将不胜感激。

我认为这将满足您的需求,但function不是“自我添加”。

public class Recorder { private IList _recording; public Recorder() { _recording = new List(); } public void CallAndRecord(Action action) { _recording.Add(action); action(); } public void Playback() { foreach(var action in _recording) { action(); } } } //usage var recorder = new Recorder(); //calls the functions the first time, and records the order, function, and args recorder.CallAndRecord(()=>Foo(1,2,4)); recorder.CallAndRecord(()=>Bar(6)); recorder.CallAndRecord(()=>Foo2("hello")); recorder.CallAndRecord(()=>Bar2(0,11,true)); //plays everything back recorder.Playback(); 

使函数“自我添加”的一种方法是使用诸如postharp或linfu动态代理之类的AOP库,并添加一个拦截器,它将函数和args添加到数组中。 要做到这一点可能比IMO值得做的工作更多,因为上述更简单并且仍然实现了所需的function。

对此没有一个优雅的解决方案。 既然你说这些方法都有不同的签名,就没有办法将它们作为委托存储在一个数组 。 有了这个,接下来你可以尝试使用reflection,将每个参数值存储在object []中,将方法存储为MethodInfo,然后调用它。

编辑:这是我能想到的:

  private Dictionary methodCollection = new Dictionary(); public void AddMethod(MethodBase method, params object[] arguments) { methodCollection.Add(method, arguments); } private void MyMethod(int p1, string p2, bool p3) { AddMethod(System.Reflection.MethodInfo.GetCurrentMethod(), new object[] { p1, p2, p3 }); } private void MyOtherMethod() { AddMethod(System.Reflection.MethodInfo.GetCurrentMethod(), new object[] { }); } 

然后只需用method.Invoke(method.ReflectedType, args)调用method.Invoke(method.ReflectedType, args)

也许您可以使用Delegate.DynamicInvoke(Object[] obj)函数。 您可以将每个方法添加到对象数组中,然后在每个方法上循环调用DynamicInvoke。

我不确定我理解你的问题,但我认为你可以使用函数指针数组(在C#中它被称为委托)。 因此,当调用函数时,将函数指针放在列表中。 通过这种方式,您可以从列表中调用函数。 这是一些想法。 注意当您向列表( functionPointers )添加新的委托指针时,在第二个列表myParameters添加类型为Parameters新对象,该对象在名为parameters公共属性中保存函数parameters 。 这意味着委托i in list functionPointers for parameters在列表myParameters有第i个对象。 这就是您知道哪些参数适用于哪种function的方法。 可能有一些更好的解决方案,但这是另一种选择。

 delegate void NewDelegate(); class Parameter{ public ArrayList parameters; } ArrayList functionPointers=new ArrayList(); ArrayList myParameters=new ArrayList(); NewDelegate myDelegate; void someFunction(int a, int b){ myDelegate+=someFunction;//you add this function to delegate because this function is called functionPointers.add(myDelegate);//Add delegete to list Parameter p=new Parameter();//Create new Parameter object p.parameters.add(a);//Add function parameters p.parameters.add(b); myParameters.add(p);//add object p to myParameters list 

}

您可以考虑使用操作或function列表

 using System; using System.Collections.Generic; namespace ReplayConsole { class Program { private static IList _actions; static void Main(string[] args) { _actions = new List { () => { //do thing }, () => { //do thing }, () => { //do thing }, () => { //do thing }, }; foreach (var action in _actions) { action(); } } } 

如果你想存储参数,你可以使用Func并以相同的方式存储和使用它

您还可以查看任务

编辑:

看着我写作时出现的答案,这个解决方案与Brook的非常相似