我想实现一个任务列表的功能 我创建了一个Delegate对象 public delegate void FuncDelegate(int parm); 和一个List List<Func> m_FuncList; 现在我想在程序开始的时候将10个不同参数的Func调用(eg. Func(1),Func(2),...Func(10))添加到List<Func>中 然后新建一个Thread去逐一执行List中的Func函数 请问我应该如何实现呢 我对代理这块还不是很熟 我这么写 m_FuncList.Add(Func) 会报错 但是我Func确实和FuncDelegate的签名一致啊 如果我先FuncDelegate FuncTask = new FuncDelegate(Func)定义一个代理 然后m_FuncList.Add(FuncTask)的话 我又如何指定不同的参数呢?
static void Test()
{
List< CallEntry > callEntryList = new List<CallEntry>();
for(int i=0; i<10; i++)
{
callEntryList.Add( new CallEntry( p => p+p, i) );
} foreach (CallEntry callEntry in callEntryList)
{
int result = callEntry.Function(callEntry.Parameter);
//int result = callEntry.Excute();
}
}public struct CallEntry
{
public Func<int, int> Function;
public int Parameter; public CallEntry(Func<int,int> funtion, int parameter){this.Function = funtion; this.Parameter = parameter;}
public int Excute() { return this.Function(this.Parameter); }
}
public interface IExecutable
{
public object Execute();
}然后用List< IExecutable >来存放所有任务。
{
static void Main(string[] args)
{
List<FuncDelegate> list = new List<FuncDelegate>();
list.Add((FuncDelegate)delegate(object parm) { Console.WriteLine("当前的parm是{0}", parm); });
list.Add((FuncDelegate)delegate(object parm) { Console.WriteLine("当前的parm是{0}", parm); });
list.Add((FuncDelegate)delegate(object parm) { Console.WriteLine("当前的parm是{0}", parm); }); new Thread(new ParameterizedThreadStart(list[0])).Start(123);
new Thread(new ParameterizedThreadStart(list[1])).Start("abc");
new Thread(new ParameterizedThreadStart(list[2])).Start(new Test("这是一个示例")); Console.ReadLine();
} public delegate void FuncDelegate(object parm);
} public class Test
{
public Test(string Name)
{
this.name = Name;
} string name; public override string ToString()
{
return string.Format("这个类是{0},传进来的Name是{1}", this.GetType(), this.name);
}
}
static void Main(string[] args)
{
List<FuncDelegate> list = new List<FuncDelegate>();
for (int i = 0; i < 10; i++)
{
list.Add(new FuncDelegate(j => { Console.WriteLine(j); }));
}
Thread th = new Thread(new ParameterizedThreadStart(o => { for (int i = 0; i < list.Count; i++) { list[i](i); } }));
th.Start();
Console.Read();
}
public delegate void FuncDelegate(int parm);