CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Nov 2005
    Posts
    102

    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??

  2. #2
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,016

    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.
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured