Using Reflection To Convert A Dynamic Type To An Object

  • Thread starter Thread starter Bob Bryan
  • Start date Start date
B

Bob Bryan

Hi,

I am working on a project where my users will be extending the capabilities
of the software by writing classes in their .NET language of choice. I have
a base class called Strategy that will be used as the base class for each
new class that they write. The Strategy class contains 2 public methods -
PrepareToExecute and Execute that can be over-ridden by each new user's
class. PrepareToExecute can contain any number of arguments of any type as
chosen by the user. Execute contains no arguments and its signature will
always be the same.

I was planning on using the .NET reflection class to query the assembly for
the signature of the PrepareToExecute method for each new class written by a
user and then to call it using a late-binding dynamic invocation. I have
found examples on how to do this and don't expect this to be a problem.

However, the Execute method will be called at least 1000 times for each
invocation of PrepareToExecute. So, I would like to use an early binding
polymorhic method to make this call. If I were doing this in C++, I would
set up a framework where the user would provide an object creation method
for his new class (and will use this method here if necessary). However, I
was hoping to save my user's from this work and instead was hoping that the
Reflection class would allow converting a type to an object. But, I don't
see how to do this.

I tried doing a cast of a type object to its base class as a test as
follows:

Type TStrat = typeof(TestStrat);
Strategy BaseStrat = (Strategy)TStrat; // Strategy is the base class of
TestStrat.
BaseStrat.Execute(); // Use polymorphism to call TStrat's Execute function.

But, the compiler complained that it could not convert System.Type to
BaseStrat. So, I guess my question is - is it possible to cast or convert a
reflection Type object to the type's base class and then to make polymorphic
calls on that object? If so how?

Thanks for any insight,

Bob Bryan
 
You cannot convert the type, you need to create an instance of the type
before convert it to Strategy.
Check out Activator.CreateInstance. Something like this:

Strategy BaseStrat = (Strategy) Activator.CreateInstance(TStrat);

Hope it helps,
Thi
 
Back
Top