这三种方法是:匿名方法、object 参数、实例方法,下面的示例分别为 thread1、thread2、thread3 演示。private void button1_Click(object sender, EventArgs e)
{
Data data = new Data();
data.Name = "千一网络";
Thread thread1 = new Thread(delegate() {
Console.WriteLine(data.Name);
});
thread1.Start();
Thread thread2 = new Thread(MyThread);
thread2.Start(data);
Thread thread3 = new Thread(data.MyThread);
thread3.Start();
}
public class Data
{
public string Name { get; set; }
public void MyThread()
{
Console.WriteLine(Name);
}
}
public void MyThread(object obj)
{
Console.WriteLine((obj as Data).Name);
}
其中,第二种方法不是类型安全的,比如把 thread2.Start(data); 改为 thread2.Start("cftea");,编译时也不会报错,因为 object 是任意类型的基础,它接受字符串,但是在运行时 (obj as Data) 就要出错了,不能把字符串转换成 Data 嘛。