我想将函数 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/