I have a class "Worker" with an entry method
internal void Run()
{
//do stuff...
}
I have a subclass for testing ("TestWorker:Worker") with an entry method
internal void Run(object aParam)
{
//do something with aParam, then..
Run();
}
I have a test app which launches an instance of TestWorker in a new thread,
Worker worker;
Thread workerThread;
...
worker = new TestWorker();
workerThread = new Thread(new ParameterizedThreadStart(worker.Run));
workerThread.Start("something");
This won't compile, and the compiler reports that the parameterized delegate (in my subclass) cannot be found. I can overcome the problem by declaring a dummy virtual Run(object) method in my Worker class such that my TestWorker.Run(object) overrides it but IMHO it is an inelegant solution, so why do I have to do this? Is it a compiler idiosyncrasy, or am I doing something logically incorrect?
The problem is that the compile-time type of worker
is just Worker
- and there isn't a Worker.Run
method accepting a parameter.
This has nothing to do with delegates per se - you wouldn't be able to call
worker.Run("foo");
either. The simplest way to fix this is just to change the declaration of worker
to be TestWorker
. Alternatively, use a separate local variable:
TestWorker testWorker = new TestWorker();
workerThread = new Thread(new ParameterizedThreadStart(testWorker.Run));
worker = testWorker;
See more on this question at Stackoverflow