frankie
frankie

Reputation: 728

How get correct type of T

I have some code like this:

    Private Shared Function ReStoreFromXML(Of T)(ByVal TargetType As T, ByVal XMLpath As String) As List(Of T)

        If Not TypeSupported(TargetType) Then Return Nothing
....
        Return CType(mySerializer.Deserialize(fstream), List(Of T))

TargetType is, for example, MyCustomType.

TypeSupported should check if TargetType is ok. When I try something like

TargetType.GetType 

Or

GetType(T)

I get only System.RuntimeType or System.Type. How can I fix this issue?

UPD:

For more clearly understanding what I want... also in method ReStoreFromXML I have such code:

 Dim mySerializer As XmlSerializer
 mySerializer = New XmlSerializer(GetType(T)) 

How can I create mySerializer with argument MyCustomType?

Upvotes: 3

Views: 3060

Answers (2)

sloth
sloth

Reputation: 101032

I call my function in such way viewsList = ReStoreFromXML(GetType(MyCustomType), XMLpath)

That's your problem. If you call ReStoreFromXML(GetType(string), ...), then T will be Type/RuntimeType. If you call ReStoreFromXML("somestring", ...), T will be string.

So just remove the first parameter, as it's unnecessary since you already know the type by calling GetType(T).

Private Shared Function ReStoreFromXML(Of T)(XMLpath As String) As List(Of T)
    Dim mySerializer = New XmlSerializer(GetType(T)) 
    ...
End Function

ReStoreFromXML(Of MyCustomType)(XMLpath)

Upvotes: 3

SWeko
SWeko

Reputation: 30872

The type should be the type argument to the function, not an argument of that type. (Yes, it's confusing).

This way you are stating the type twice, so a reasonable call will be:

ReStoreFromXML(Of String)("somestring", xmlPath)

Where the "somestring" is only used to check that it's indeed a string, and that's already stated in the (Of String) part.

You should change the signature of the method to:

Private Shared Function ReStoreFromXML(Of T)(ByVal XMLpath As String) As List(Of T)
    If Not TypeSupported(T) Then Return Nothing
    ...
End Function

Upvotes: 1

Related Questions