2011-02-06 68 views
0

即時通訊嘗試在C#中創建ConsoleApplication。現在我正在研究一個綁定系統,它會讀取您輸入的密鑰,並在綁定時採取操作。列表可以包含多個void方法嗎?

到目前爲止,我創建了一個struct Binded,持有一個ConsoleKey和一個void Action(),並且我做了一個List Binds將它放在一個整齊的列表中。

public struct Binded 
     { 
      public ConsoleKey Key; 
      public void Action() 
      { 
//Whatever 
      } 
     } 
List<Binded> Binds 

然後我只是添加我想要使用的鍵以及我希望他們採取的操作。現在我可以添加鍵很好,但似乎我無法爲每個鍵設置不同的Action()。 如果你知道有什麼問題,或者你有更好的想法如何做到這一點,我很想聽到它,提前謝謝。

+5

不要爲此使用結構。 – SLaks 2011-02-06 00:54:04

回答

5

首先,我建議使用類,而不是一個結構(或使這一不可改變的)。

也就是說,您可以通過定義此操作來將操作委託給操作,而不是在結構/類本身中定義操作。

例如:

public class Binding 
{ 
    public Binding(ConsoleKey key, Action action) 
    { 
      this.Key = key; 
      this.Action = action; 
    } 
    public ConsoleKey Key { get; private set; } 
    public Action Action { get; private set; } 
} 

然後,你會怎麼做:

public List<Binding> Binds; 

// Later... 
Binds.Add(new Binding(ConsoleKey.L,() => 
    { 
     // Do something when L is pressed 
    }); 
Binds.Add(new Binding(ConsoleKey.Q,() => 
    { 
     // Do something when Q is pressed 
    }); 
+0

謝謝,這正是我正在尋找的。 – SaintHUN 2011-02-06 01:07:11

2

你應該Action類型的屬性(這是一個委託類型)

0

像這樣的東西應該做的伎倆。

using System; 
using System.Collections.Generic; 

namespace ActionableList 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      List<Actionable> actionables = new List<Actionable> 
      { 
       new Actionable 
        { 
         Key = ConsoleKey.UpArrow, 
         Action = ConsoleKeyActions.UpArrow 
        }, 
       new Actionable 
       { 
        Key = ConsoleKey.DownArrow, 
        Action = ConsoleKeyActions.DownArrow 
       }, 
       new Actionable 
       { 
        Key = ConsoleKey.RightArrow, 
        Action = ConsoleKeyActions.RightArrow 
       }, 
       new Actionable 
       { 
        Key = ConsoleKey.UpArrow, 
        Action = ConsoleKeyActions.UpArrow 
       } 
      }; 

      actionables.ForEach(a => a.Action()); 

      Console.ReadLine(); 
     } 
    } 

    public class Actionable 
    { 
     public ConsoleKey Key { get; set; } 
     public Action Action { get; set; } 
    } 

    public static class ConsoleKeyActions 
    { 
     public static void UpArrow() 
     { 
      Console.WriteLine("Up Arrow."); 
     } 

     public static void DownArrow() 
     { 
      Console.WriteLine("Down Arrow."); 
     } 

     public static void LeftArrow() 
     { 
      Console.WriteLine("Left Arrow."); 
     } 

     public static void RightArrow() 
     { 
      Console.WriteLine("Right Arrow."); 
     } 
    } 
} 
相關問題