在c中实现委托

本文关键字:实现 | 更新日期: 2023-09-27 18:22:05

这将是我第一次在c#中使用委托,所以请耐心等待。我读了很多关于它们的文章,但直到现在还没有想过如何/为什么使用这个构造。

我有一些代码看起来像这样:

public class DoWork()
{
   public MethodWorkA(List<long> TheList) {}
   public void MethodWork1(parameters) {}
   public void MethodWork2(parameters) {}
}

我从类外的方法调用MethodWorkA,MethodWorkA调用MethodWork 1和2。当我调用methodA时,我想传递某种参数,这样它有时只执行MethodWork1,有时同时执行MethodWork2和MethodWork1。

所以当我打电话时,它看起来是这样的:

DoWork MyClass = new DoWork();
MyClass.MethodA...

委托语法在哪里合适?

谢谢。

在c中实现委托

public void MethodWorkA(Action<ParamType1, ParamType2> method) {
    method(...);
}

您可以使用方法组转换来调用它:

MethodWorkA(someInstance.Method1);

您还可以创建一个调用两种方法的多播委托:

MethodWorkA(someInstance.Method1 + someInstance.Method2);

对于您所描述的内容,您不需要委托。

只需这样做:

public class DoWork
{
    public void MethodWorkA(List<long> theList, bool both) 
    {
        if (both)
        {
            MethodWork1(1);
            MethodWork2(1);
        }
        else MethodWork1(1);
    }
    public void MethodWork1(int parameters) { }
    public void MethodWork2(int parameters) { }
}

如果你只是在试验代表,下面是:

public partial class Form1 : Form
{
    Func<string, string> doThis;
    public Form1()
    {
        InitializeComponent();
        Shown += Form1_Shown;
    }
    void Form1_Shown(object sender, EventArgs e)
    {
        doThis = do1;
        Text = doThis("a");
        doThis = do2;
        Text = doThis("a");
    }
    string do1(string s)
    {
        MessageBox.Show(s);
        return "1";
    }
    string do2(string s)
    {
        MessageBox.Show(s);
        return "2";
    }
}

考虑到所有方法都在同一个类中,并且您使用该类的实例调用MethodWorkA函数,老实说,我看不出使用Action<T>delegate有任何原因,因为我理解您的问题。

当我调用methodA时,我想传递某种参数,以便有时它只做MethodWork1,有时两者都做MethodWork1和MethodWork2。

为什么不把一个简单的参数传递给MethodWorkA,比如

public class DoWork()
{
   public enum ExecutionSequence {CallMethod1, CallMethod2, CallBoth};
   public MethodWorkA(List<long> TheList, ExecutionSequence exec) 
   {
       if(exec == ExecutionSequence.CallMethod1) 
         MethodWork1(..);
       else if(exec == ExecutionSequence.CallMethod2)
         MethodWork2(..);
       else if(exec == ExecutionSequence.Both)
       {
          MethodWork1(..);
          MethodWork2(..);
       } 
   }
   public void MethodWork1(parameters) {}
   public void MethodWork2(parameters) {}
}

对于你的阶级消费者来说,这更简单易懂。

如果这不是你想要的,请解释。

编辑

只是给你一个你能做什么的想法:

示例:

public class Executor {
     public void MainMethod(long parameter, IEnumerable<Action> functionsToCall) {
            foreach(Action action in functionsToCall) {
                  action();
            }
     }
}

并且在代码中

void Main()
{
    Executor exec = new Executor();
    exec.MainMethod(10, new List<Action>{()=>{Console.WriteLine("Method1");}, 
                                         ()=>{Console.WriteLine("Method2");}
    });
}

输出将是

Method1
Method2

例如,通过这种方式,您可以将只想执行的函数推入集合。当然,在这种情况下,决策逻辑(必须执行哪些函数)是在调用之外确定的。