2016-07-18 35 views
0

2つの文字列の代わりにTagContactByMailをSetTimerに渡します。2つの引数を持つパラメータとしてvoid関数を渡します。

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

これは私がのSetTimerにパラメータとして渡す機能です。代わりに、私はそれを2つの文字列を受け取り、何も返さないTagContactByMailような関数を渡したいのSetTimer 2文字列に渡すの

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

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

使用Action(T1, T2)

は、2つのパラメータを受け取り、戻り値を持たないメソッドをカプセル化します。

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

私はTagContactByMailに変数を渡すにはどうすればよいですか? –

+0

@ OffirPe'er他の方法でやっているように。あなたのケースでは、 'SetTimer'メソッドの中で' handle(contactEmail、tagName) 'を持っています –

+0

もっとコードを使って答えを編集することはできますか? –

関連する問題