为什么TryCast不接受t作为Type?
Private Async Function DeSerialize(FilePath As String, t As Type) As Task(Of Object)
Dim ReadStream = Await Windows.ApplicationModel.Package.Current.InstalledLocation.OpenStreamForReadAsync(FilePath)
Dim Sarjoittaja As New Runtime.Serialization.DataContractSerializer(GetType(UITextsClass))
Return TryCast(Sarjoittaja.ReadObject(ReadStream), t)
End Function
仍然没有那么多:
Public Async Function DeSerialize(Of T)(FilePath As String) As Task(Of T)
Dim ReadStream = Await Windows.ApplicationModel.Package.Current.InstalledLocation.OpenStreamForReadAsync(FilePath)
Dim Sarjoittaja As New Runtime.Serialization.DataContractSerializer(T) 'T' is a Type and cannot be used as an expression
Return DirectCast(Sarjoittaja.ReadObject(ReadStream), T)
End Function
答案 0 :(得分:2)
您使用Generic Type的语法有点偏差: - 您需要在参数之前定义泛型类型并返回此类型,如下所示:
Private Async Function DeSerialize(Of T)(FilePath As String) As Tasks.Task(Of T)
'Read and Deserialize
Dim ReadStream = Await Windows.ApplicationModel.Package.Current.InstalledLocation.OpenStreamForReadAsync(FilePath)
Dim Sarjoittaja As New Runtime.Serialization.DataContractSerializer(GetType(UITextsClass))
Return TryCast(Sarjoittaja.ReadObject(ReadStream), T)
End Function
有关详细信息,请参阅docs on MSDN
答案 1 :(得分:1)
TryCast
运算符以及CType
和DirectCast
对类型名称而不是System.Type
的实例进行操作。
如果您的基础设施允许,请将此方法转换为通用方法。
Private Async Function DeSerialize(Of T)(FilePath As String) As Task(Of T)
'Read and Deserialize
Dim ReadStream = Await Windows.ApplicationModel.Package.Current.InstalledLocation.OpenStreamForReadAsync(FilePath)
Dim Sarjoittaja As New Runtime.Serialization.DataContractSerializer(GetType(UITextsClass))
Return TryCast(Sarjoittaja.ReadObject(ReadStream), T)
End Function
回复:评论
我不确定这是否是您要问的内容,但您可以使用GetType()
运算符获取传入的类型。
Dim t As Type = GetType(T)
Dim Sarjoittaja As New Runtime.Serialization.DataContractSerializer(t)