简体   繁体   中英

Using a string name for an object and an assembly

I'm not great with reflection and I hope I chose the right category. I have an interesting problem. I have written a report using devexpress reports. This involves a line of code like this:

lxListData = New System.Collections.Generic.List(Of DLL.Report.ListData) 

ListData is report in an assembly external to the one where the above line is executed. The above line works fine and allows me to run the report.

What I've done is put all the information for this report into a table as strings, That includes the type:" DLL.Report.ListData"

What I need is to change this string name into the type used in the line of code above. I have tried:

Dim type1 As Type = System.Reflection.Assembly.LoadWithPartialName("DLL.Report").GetType("DLL.Report.ListData")

and then changing the line above to:

lxListData = New System.Collections.Generic.List(Of type1) 

I've tried a few other techniques that are similar. In all cases the "type1" variable is not seen as a type even though it looks like it is in the watch window.

Any advice would be appreciated.

Thanks, Neil

I've done some more research and found that this line:

Dim type1 As Type = System.Reflection.Assembly.LoadWithPartialName("DLL.Report").GetType("DLL.Report.ListData")

It returns a sytem.type in the variable type1, not type DLL.Report.ListData. Within that variable are two properties: Name="ListData" and FullName="DLL.Report.ListData". I was able to use some methods that were in type1 to get the properties of DLL.Report.ListData so type1 seems to be a pointer to DLL.Report.ListData. My problem is that I need a variable that is type DLL.Report.ListData. Is there a way to take the Fullname string and return something that is the type DLL.Report.ListData instead of "system.type"?

Here's how:

Dim list As IList = _
    Ctype(Activator.CreateInstance(GetType(List(Of )).MakeGenericType(type1)), IList)

Keep in mind that since you are creating this at run-time that you can't have strong-typing at compile-time. The best you can do is make this an IList .

The other option, if you want to work with a strongly-typed list, is to call a generic method using reflection. Work done within the method is strongly-typed.

Dim mi = Me.GetType().GetMethod("CreateList")
Dim gmi = mi.MakeGenericMethod(type1)
Dim list = Ctype(gmi.Invoke(Me, Nothing), IList)

Public Function CreateList(Of T) As List(Of T)
    ' Strongly-typed to `T` in here
    Return New List(Of T)()
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM