call method in dynamic object?
Hi, i have some sort of Factory class which creates an instance of another class like so:
Code:
public object setDispatcher ( string obj )
{
this.dispatcher = Activator.CreateInstance(Type.GetType(obj));
return this.dispatcher;
}
//This is how i use the method
object disp = setDispatcher ( "MyClass" );
As parameter i gave the name of the Class which i want to instantiate. It works this far, because the constructor is called of the dynamically created class.
The instance of "MyClass" is now stored in the variable 'disp', but obviously i can't just do this:
disp.aMethod();
Because the compiler doesn't know what class i want to have and what methods it has. So there must be some other way to call the methods??
Anyone any advice on this??
Re: call method in dynamic object?
This design pattern feels broken to me. I'm not sure why you would want to do this (i.e. use a factory to return an object instead of a typed class). Could you give some context as to what you are doing?
Also, the dumb answer is you should cast it to the object type...
Code:
object disp = setDispatcher ( "MyClass" );
MyClass myclassDisp = (MyClass)disp;
myclassDisp.methodCall();
... but I assume that isn't what you meant.