Converting Types from reflection

  • Thread starter Thread starter Larry R
  • Start date Start date
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
 
'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)
 
Back
Top