-4

我从旧帖子中获得了此代码

public delegate void Worker();
private static Thread worker;

public static void Init(Worker work)
{
    worker = new Thread(new ThreadStart(work));
    worker.Start();
}

public static void Work()
{
    string result = testing;
}

我通过添加参数来修改代码,当我尝试调用 Init("AA") 时出现错误“最佳重载方法有一些无效参数”

以下是编辑后的代码

    public delegate void Worker();
private static Thread worker;

public static void Init(Worker work)
{
    worker = new Thread(new ThreadStart(work));
    worker.Start();
}

public static void Work(string testing)
{
    string result = testing;
}
4

3 回答 3

2

您的Init方法需要一个委托并且您正在传递一个字符串,这就是没有重载的原因。

你想做:Init(Work)

PS:您的问题与线程无关。

于 2012-12-17T09:29:03.697 回答
0

如果您想将一些数据传递给线程,您可以使用ParametrizedThreadStart或匿名方法:

private static Thread worker;

public static void Init(string testing)
{
    // passing anonymous method, which will capture parameter
    worker = new Thread(() => Work(testing));
    worker.Start();
}

public static void Work(string testing)
{
    string result = testing;
}

private static Thread worker;

public static void Init(string testing)
{
    // passing PrametrizedThreadStart delegate
    worker = new Thread(Work);
    worker.Start(testing); // passing parameter
}

// PrametrizedThreadStart delegate accepts object as parameter
public static void Work(object testing)
{
    string result = (string)testing;
}
于 2012-12-17T09:31:10.183 回答
0

问题是您的Worker代表期望接受一个string参数。您需要更新它,然后传入参数,例如

public delegate void Worker(string str);
private static Thread worker;
public static void Init(Worker work)
{
    worker = new Thread(work);
    worker.Start("AA");
}
public static void Work(string testing)
{
    string result = testing;
}
于 2012-12-17T09:33:25.910 回答