I am invoking a method with parameter using reflection (dynamic to be precise). No problem with the invokation when parameter of the method and arguments passed match at compile time; but if i use a base type (in the signature, at runtime types always match), event if a runtime parameter match i get error (at runtime).
Example below :
public class WorkerAbstraction
{
object _actualWorker = null;
public WorkerAbstraction (object actualWorker)
{
_actualWorker = actualWorker;
}
public void DoWorkAbs ( AbstractBaseClass args )
{
((dynamic)_actualWorker).DoWork (args); //--> here is where the exception is rised
}
}
public class ActualWorker<T> where T : AbstractBaseClass
{
public void DoWork ( T args )
{
...
}
}
public class Person : AbstractBaseClass { ... }
Now if i test the code above that way :
WorkerAbstraction wab = new WorkerAbstraction ( new ActualWorker<Person> () );
Person person = new Person();
wab.DoWorkAbs (person);
Then i get that exception :
The best overloaded method match for 'ActualWorker.DoWork(Person)' has some invalid arguments.
I have checked at runtime, when exception is rised (in DoWorkAbs) : _actualWorker is ActualWorker args is Person
Then i have modified the code and checked it again :
public void DoWorkAbs ( AbstractBaseClass args )
{
((dynamic)_actualWorker).DoWork ((Person)args); //--> that explicit cast solve the problem
}
What i don't understand is the origin of the problem. Ok that aproach is not 100% safe, but in my case in both scenario object and parameter are correct at runtime.
So what's going on?
-----Edit : itegrated a working example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestReflection
{
class Program
{
static void Main(string[] args)
{
Person person = new Person() { Name = "Michelle" };
WorkerAbstraction wab = new WorkerAbstraction(new ActualWorker<Person>());
wab.DoWorkAbs(person);
Console.ReadKey();
}
}
public class WorkerAbstraction
{
object _actualWorker = null;
public WorkerAbstraction(object actualWorker)
{
_actualWorker = actualWorker;
}
public void DoWorkAbs(AbstractBaseClass args)
{
((dynamic)_actualWorker).DoWork(args); // --> raise exception
//((dynamic)_actualWorker).DoWork((Person)args); // --> working fine
}
}
public class ActualWorker<T> where T : AbstractBaseClass
{
public void DoWork(T args)
{
args.SayHello();
}
}
public class Person : AbstractBaseClass
{
public Person()
{
}
public string Name { get; set; }
public override void SayHello()
{
Console.WriteLine ($"{this.Name} say hello.");
}
}
public abstract class AbstractBaseClass
{
public abstract void SayHello();
}
}