C# 线程 -ThreadStart 委托
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1782210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Threads -ThreadStart Delegate
提问by user215675
The execution of the following code yields error :No overloads of ProcessPerson Matches ThreadStart.
以下代码的执行产生错误:ProcessPerson 没有重载匹配 ThreadStart。
public class Test
{
static void Main()
{
Person p = new Person();
p.Id = "cs0001";
p.Name = "William";
Thread th = new Thread(new ThreadStart(ProcessPerson));
th.Start(p);
}
static void ProcessPerson(Person p)
{
Console.WriteLine("Id :{0},Name :{1}", p.Id, p.Name);
}
}
public class Person
{
public string Id
{
get;
set;
}
public string Name
{
get;
set;
}
}
How to fix it?
如何解决?
采纳答案by Jon Skeet
Firstly, you want ParameterizedThreadStart
- ThreadStart
itself doesn't have any parameters.
首先,您想要ParameterizedThreadStart
-ThreadStart
本身没有任何参数。
Secondly, the parameter to ParameterizedThreadStart
is just object
, so you'll need to change your ProcessPerson
code to cast from object
to Person
.
其次,参数 toParameterizedThreadStart
只是object
,因此您需要将ProcessPerson
代码更改为从object
to 转换Person
。
static void Main()
{
Person p = new Person();
p.Id = "cs0001";
p.Name = "William";
Thread th = new Thread(new ParameterizedThreadStart(ProcessPerson));
th.Start(p);
}
static void ProcessPerson(object o)
{
Person p = (Person) o;
Console.WriteLine("Id :{0},Name :{1}", p.Id, p.Name);
}
However, if you're using C# 2 or C# 3 a cleaner solution is to use an anonymous method or lambda expression:
但是,如果您使用的是 C# 2 或 C# 3,一个更简洁的解决方案是使用匿名方法或 lambda 表达式:
static void ProcessPerson(Person p)
{
Console.WriteLine("Id :{0},Name :{1}", p.Id, p.Name);
}
// C# 2
static void Main()
{
Person p = new Person();
p.Id = "cs0001";
p.Name = "William";
Thread th = new Thread(delegate() { ProcessPerson(p); });
th.Start();
}
// C# 3
static void Main()
{
Person p = new Person();
p.Id = "cs0001";
p.Name = "William";
Thread th = new Thread(() => ProcessPerson(p));
th.Start();
}
回答by Richard Nienaber
Your function declaration should look like this:
您的函数声明应如下所示:
static void ProcessPerson(object p)
Inside ProcessPerson
, you can cast 'p' to a Person
object.
在里面ProcessPerson
,您可以将 'p' 转换为一个Person
对象。