0

正如您在我的代码中看到的那样,我想将一个方法保存(设置)到一个对象中。并使用该对象调用该方法...

请看代码,您可以轻松理解;用简单的英语很难解释...

我的问题是;当然“动作操作”对象不能保存将被调用的方法。

那么,我该如何解决这个问题呢?我能做些什么?


...
    enum CampaignUserChoice
    {
        Insert,
        Update,
        Delete,
        Disable
    }

private void AskUserAboutCampaignOperation(CampaignUserChoice choice) { string questionForUser = string.Empty; string questionTitleForUser = string.Empty; Action operation; //<<<<--------------------- this line, it's method holder if (choice == CampaignUserChoice.Insert) { questionForUser = "Do you want to create a new campaign?"; questionTitleForUser = "NEW CAMPAIGN"; operation = InsertCampaign(TakeDatasFromGui()); //<---------- set which method you want to call } else { operation = UpdateCampaign( campaignId, TakeDatasFromGui()); } //TODO write other elses... switch (MessageBox.Show(questionForUser, questionTitleForUser, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)) { case DialogResult.Yes: operation; //<<<------------------ call method here... break; case DialogResult.No: // "No" processing break; case DialogResult.Cancel: // "Cancel" processing break; } }

非常感谢大家的回答...

4

3 回答 3

2

您正在尝试使用代表

operation = TakeDataFromGui;
...
operation();
于 2012-05-31T12:04:08.993 回答
1

使用lambda 表达式来分配委托:

operation = () => InsertCampaign(TakeDatasFromGui()); 

像常规函数一样调用动作:

operation()
于 2012-05-31T12:15:01.317 回答
1

您需要 委托来调用方法

  //declare delegate declaration same as function
   delegate returntype delegate_name(parameter1,paramenter2,..);

   //assaign function to  delegate
   delegate_name=function();

   //call function
   delagate_name();
于 2012-05-31T12:21:04.597 回答