将void函数作为参数传递两个参数

时间:2016-07-18 13:54:50

标签: c# delegates

我想将函数 TagContactByMail 传递给SetTimer而不是2个字符串。

 public void AddTagToContact(string tagName, string contactEmail)
        {
                SetTimer(tagName, contactEmail);
                aTimer.Dispose();
        }

这是我想作为参数传递给 SetTimer 的函数。

private void TagContactByMail(string contactEmail, string tagName)
    {
        //Stop timer.
        aTimer.Stop();

        //If the time passed or we successfuly tagged the user. 
        if (elapsedTime > totalTime || tagSuccess)
        {
            return;
        }

        //Retrieve the Contact from Intercom by contact email.
        Contact contact = contactsClient.List(contactEmail).contacts.FirstOrDefault();

        //If Contact exists then tag him.
        if (contact != null)
        {
            tagsClient.Tag(tagName, new List<Contact> { new Contact() { id = contact.id } });
            tagSuccess = true;
            return;
        }

        //If Contact doesn't exist then try again.
        aTimer.Enabled = true;
        elapsedTime += interval;
    }

我想传递一个像 TagContactByMail 这样的函数,而不是传递给SetTimer 2字符串,它需要2个字符串并且不会返回任何内容。

 private void SetTimer(string tagName, string contactEmail)
        {
            //Execute the function every x seconds.
            aTimer = new Timer(interval);
            //Attach a function to handle.
            aTimer.Elapsed += (sender, e) => TagContactByMail(contactEmail, tagName);
            //Start timer.
            aTimer.Enabled = true;
        }

我希望 SetTimer 是通用的,所以我也可以发送其他功能,我该怎么做?

1 个答案:

答案 0 :(得分:1)

使用Action(T1, T2)

  

封装具有两个参数且不返回值的方法。

private void SetTimer(Action<string, string> handle)
{
    // ...
}

您可以这样致电SetTimer

SetTimer(TagContactByMail);

修改

如果您期待的是传递使用这两个参数准备的方法,那么您只需要在不知道实际参数的情况下从SetTimer调用它,您可以这样做:

private void SetTimer(Action handle)
{
    //Execute the function every x seconds.
    aTimer = new Timer(interval);

    //Attach a function to handle.
    aTimer.Elapsed += (sender, e) => handle();

    //Start timer.
    aTimer.Enabled = true;
}

然后,你可以这样打电话给SetTimer

public void AddTagToContact(string tagName, string contactEmail)
{
    SetTimer(() => TagContactByMail(contactEmail, tagName));
    aTimer.Dispose();
}
相关问题