List可以包含多个void方法吗?

ptr*_*x01 0 c# console list void

我试图在C#中创建一个ConsoleApplication.现在我正在研究一个绑定系统,该系统将读取您输入的密钥并在绑定时执行操作.

到目前为止,我创建了一个struct Binded,它包含一个ConsoleKey和一个void Action(),我创建了一个List Binds,将它放在一个整齐的列表中.

public struct Binded  
        {   
            public ConsoleKey Key;  
            public void Action()  
            {  
//Whatever  
            }  
        }  
List<Binded> Binds
Run Code Online (Sandbox Code Playgroud)

然后我只添加我想要使用的密钥以及我希望他们采取的操作.现在我可以添加键很好但似乎我无法为每个键设置不同的Action().如果您知道问题是什么,或者您对如何做到这一点有了更好的想法,我很想听到它,提前谢谢.

Ree*_*sey 5

首先,我建议使用类而不是结构(或使其成为不可变的).

话虽这么说,你可以通过定义这个来获取一个委托给动作,而不是在struct/class本身中定义Action.

例如:

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; }
}
Run Code Online (Sandbox Code Playgroud)

然后你会做:

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
   });
Run Code Online (Sandbox Code Playgroud)