Converting Types from reflection

L

Larry R

I am trying to use a config file to determine which class to use in the
following statement:

Dim tp as new TimePeriod ' this is a class that uses a strategy
pattern
tp. SetTimeStrategy ( new HourStrategy) 'HourStrategy is a
"TimePeriodStrategy" type

The above code works fine. What I need to do is read a variable to
determine which strategy to use.. For instance

Dim strategy As String = "HourStrategy"

Dim strategyType As Type
strategyType = Type.GetType("NamespaceHere." & strategy)

Dim tp as new TimePeriod ' this is a class that uses a strategy
pattern
'this is what I need here
tp. SetTimeStrategy ( new strategyType )

I have tried the DirectCast() and some others, but can't get it to work
because the parameter to the SetTimeStrategy is strongly typed.

What am I missing here? How do I convert a type to a custom object
type?

Thanks

Larry
 
T

Tim Van Wassenhove

'this is what I need here
tp. SetTimeStrategy ( new strategyType )

I don't really understand, do you want to pass an instance of
System.Type or an instance of the strategyType?

The second can be solved as following:

Strategy s1 = Assembly.CreateInstance("mystrategy")
Strategy s2 = System.Activator.CrateInstance("mystrategy",
"uritoassembly")

tp.setTimeStrategy(s1)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top