- using System; using System.Threading;
- namespace ThreadWithParameters {
- class Program {
- static void Main(string[] args) {
- string hello = "hello world"; //如果写成Thread thread = new Thread(ThreadMainWithParameters(hello));这种形式,编译时就会报错
- Thread thread = new Thread(() => ThreadMainWithParameters(hello)); thread.Start();
- Console.Read(); }
- static void ThreadMainWithParameters(string str) {
- Console.WriteLine("Running in a thread,received: {0}", str); }
- } }
哇,你会发现既不用类型强制转换也不用新建类就运行成功了。
但是为什么这种方式能行呢,根据昨天 @乱舞春秋 的提示,我也用ildasm反编译了一下,确实如他所说,我所谓的第三种方式其实和第二种方式是一样的,只不过自定义类编译器帮我们做了。
下面的是第三种方式main方法反编译的IL代码:
- .method private hidebysig static void Main(string[] args) cil managed {
- .entrypoint // 代码大小 51 (0x33)
- .maxstack 3 .locals init ([0] class [mscorlib]System.Threading.Thread thread,
- [1] class ThreadWithParameters.Program/'<>c__DisplayClass1' 'CS#FormatTableID_3#lt;>8__locals2') IL_0000: newobj instance void ThreadWithParameters.Program/'<>c__DisplayClass1'::.ctor()










