Why can't I use/cast an Action for/to a Thread

2019-02-04 22:21发布

Both are delegates and have the same signature, but I can not use Action as ThreadStart.

Why?

Action doIt;
doIt = () => MyMethod("test");
Thread t;

t = new Thread(doIt);
t.Start();

but this seems to work:

Thread t;

t = new Thread(() => MyMethod("test"));
t.Start();

8条回答
The star\"
2楼-- · 2019-02-04 23:02

Try:

t = new Thread(new ThreadStart(doIt));

or

t = new Thread( ()=>MyMethod("test"));

You're trying to pass an argument of type "Action" to a constructor that takes a ThreadStart. There isn't an implicit conversion defined, so you need to manually invoke the ThreadStart constructor.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-02-04 23:04

The basic form of this error is:

delegate void d1();
delegate void d2();
d1 a;
d2 b;
b = a;

Error Cannot implicitly convert type 'ConsoleDemo1.d1' to 'ConsoleDemo1.d2'

So you could 'solve' your first sample by using the correct delegate type:

//Action doIt;
ThreadStart doIt;
doIt = () => MyMethod("test");
Thread t = new Thread(doIt);
查看更多
登录 后发表回答