c# - 将 void 函数作为带有两个实参的参数传递

标签 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;
    }

我不想传递给 SetTimer 2 个字符串,而是想传递一个像 TagContactByMail 这样的函数,它接受 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 是通用的,这样我也可以向它发送其他函数,我该怎么做?

最佳答案

使用Action(T1, T2) :

Encapsulates a method that has two parameters and does not return a value.

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();
}

关于c# - 将 void 函数作为带有两个实参的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38438578/

相关文章:

c# - Visual Studio 不再显示代码中的错误

c# - 如何告诉 JsonConvert.SerializeObject 将字符串对象视为 JSON

c# - 使用委托(delegate)从 C# 调用 IronRuby

iPhone:TabView + TableView

ios - 数据从 watch 发送到手机后未调用 Swift 3 XML 解析委托(delegate)

c# - "Base class could not be loaded"- 没有明确的原因

c# - 在桌面应用程序中本地使用哪个数据库?

c# - 在用户和服务器之间传递数据

ios - UISearchController & UISearchBar 子类

c# - 为什么我不能使用这样的匿名方法?