列表可以包含多个void方法吗?
问题描述:
即时通讯尝试在C#中创建ConsoleApplication。现在我正在研究一个绑定系统,它会读取您输入的密钥,并在绑定时采取操作。列表可以包含多个void方法吗?
到目前为止,我创建了一个struct Binded,持有一个ConsoleKey和一个void Action(),并且我做了一个List Binds将它放在一个整齐的列表中。
public struct Binded
{
public ConsoleKey Key;
public void Action()
{
//Whatever
}
}
List<Binded> Binds
然后我只是添加我想要使用的键以及我希望他们采取的操作。现在我可以添加键很好,但似乎我无法为每个键设置不同的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; }
}
然后,你会怎么做:
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
答
你应该Action
类型的属性(这是一个委托类型)
答
像这样的东西应该做的伎俩。
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.");
}
}
}
不要为此使用结构。 – SLaks 2011-02-06 00:54:04