-4

を設定しようとしてdictionaryいます。これは、のようにkeys保存されitemsますlistbox

を確立しdictionaryて、にkeys入力することはできましたlistboxが、に関連付けられたアクションを実行する方法がわかりませんkey。前のスレッドから推奨事項がありましたが、問題が発生しました:元のスレッド

Dictionary<string, Action> dict = new Dictionary<string, Action>();
public void SetDictionary()
    {
       //add entries to the dictionary
        dict["cat"] = new Action(Cat);
        dict["dog"] = new Action(Dog);

        //add each dictionary entry to the listbox.
        foreach (string key in dict.Keys)
        {
            listboxTest.Items.Add(key);
        }                            
    }

     //when an item in the listbox is double clicked
     private void listboxTest_DoubleClick(object sender, EventArgs e)
     {
         testrun(listboxCases.SelectedItem.ToString());             
     }

     public void testrun(string n)
     {
         //this is supposed to receive the item that was double clicked in the listbox, and run it's corresponding action as defined in the dictionary.
         var action = dict[n] as Action action();
     }

上記の私のコードはほとんど正しく、理解していると思いますが、アクションラインは次のとおりです。

var action = dict[n] as Action action();

'action'がを期待していることを示すエラーを示します';'。ここでの私の論理は正確ですか?もしそうなら、なぜアクションコールが正しくないのですか?

4

3 に答える 3

10

あなたが欠けている;

var action = dict[n] as Action; action();
                              ↑
于 2013-01-10T18:03:48.773 に答える
7

まず、辞書がリストされていないので、辞書の定義を想定しています。

Dictionary<string, Action> dict;

それが一致しない場合の定義を示してください。

特定のキーに対してアクションを実行するために必要なのは、次のとおりです。

dict[key]();

また

dict[key].Invoke();

それを変数として保存するには、キャストがまったく必要ありません(必要はありません)。

Action action = dict[key];

あなたがそれをキャストする必要がある場合(あなたの辞書の定義が私がリストしたものと異なることを意味します)、あなたはこのようにそうすることができます:

Action action = dict[key] as Action;

次に、上記のように呼び出すことができます。

action();

また

action.Invoke();
于 2013-01-10T18:04:29.530 に答える
1

テストランは

public void testrun(string n)
{
     //this is supposed to receive the item that was double clicked in the listbox, and run it's corresponding action as defined in the dictionary.
     dict[n]();
}

Dictionary<string, Action>あなたの辞書は@Servyが提案した通りであるという仮定に基づいています

于 2013-01-10T18:10:27.690 に答える