简体   繁体   English

在C#中实现委托

[英]implementing delegates in c#

This would be the first time I'd use delegates in c# so please bear with me. 这将是我第一次在c#中使用委托,因此请耐心等待。 I've read a lot about them but never thought of how/why to use this construct until now. 我已经阅读了很多关于它们的内容,但是直到现在为止都还没有想到过如何/为什么使用这种结构。

I have some code that looks like this: 我有一些看起来像这样的代码:

public class DoWork()
{

   public MethodWorkA(List<long> TheList) {}

   public void MethodWork1(parameters) {}

   public void MethodWork2(parameters) {}

}

I call MethodWorkA from a method outside the class and MethodWorkA calls MethodWork 1 and 2. When I call methodA, I'd like to pass some sort of parameter so that sometimes it just does MethodWork1 and sometimes it does both MethodWork1 and MethodWork2. 我从类外部的方法调用MethodWorkA,而MethodWorkA则调用MethodWork 1和2。当我调用methodA时,我想传递某种参数,以便有时只执行MethodWork1,有时同时执行MethodWork1和MethodWork2。

So when I call the call it looks like this: 因此,当我拨打电话时,它看起来像这样:

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

Where does the delegate syntax fit in this? 委托语法在哪里适合呢?

Thanks. 谢谢。

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

You can call it using method group conversion: 您可以使用方法组转换来调用它:

MethodWorkA(someInstance.Method1);

You can also create a multicast delegate that calls two methods: 您还可以创建调用两个方法的多播委托:

MethodWorkA(someInstance.Method1 + someInstance.Method2);

Considering that all methods are inside the same class, and you call MethodWorkA function using an instance of the class, I honestly, don't see any reason in using Action<T> or delegate , as is I understood your question. 考虑到所有方法都在同一个类中,并且您使用该类的实例调用MethodWorkA函数,老实说,我理解您的问题,因此看不到使用Action<T>delegate任何原因。

When I call methodA, I'd like to pass some sort of parameter so that sometimes it just does MethodWork1 and sometimes it does both MethodWork1 and MethodWork2. 当我调用methodA时,我想传递某种参数,以便有时仅执行MethodWork1,有时同时执行MethodWork1和MethodWork2。

Why do not just pass a simple parameter to MethodWorkA , like 为什么不只是将简单的参数传递给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) {}

}

Much simplier and understandable for your class consumer. 对于您的类消费者而言,这更加简单易懂。

If this is not what you want, please explain. 如果这不是您想要的,请解释。

EDIT 编辑

Just to give you an idea what you can do: 只是为了让您知道您可以做什么:

Example: 例:

public class Executor {

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

and in the code 并在代码中

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

The output will be 输出将是

Method1
Method2

In this way you, for example, can push into the collection only functions you want to execute. 例如,通过这种方式,您可以仅将要执行的功能推入集合。 Sure, in this case, the decision logic (which functions have to be executed) is determined outside of the call. 当然,在这种情况下,决策逻辑(必须执行哪些功能)是在调用之外确定的。

For what you described, you don't need delegates. 对于您描述的内容,您不需要代表。

Just do something like this: 只是做这样的事情:

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) { }
}

If you're just experimenting with delegates, here goes: 如果您只是尝试使用委托,请按以下步骤进行:

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";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM