我在另一个问题C# - How to xml deserialize object itself?上找到了此代码 我真的很喜欢这个代码,并希望在我的应用程序中使用它,但我的目标是.net 2.0 Compact框架,所以我不能使用LINQ表达式。是否有人可以告诉我如何将其转换为"普通VB"码?
来自用户wheelibin的原始代码。
我采用了这种方法:
Public Class SerialisableClass
Public Sub SaveToXML(ByVal outputFilename As String)
Dim xmls = New System.Xml.Serialization.XmlSerializer(Me.GetType)
Using sw = New IO.StreamWriter(outputFilename)
xmls.Serialize(sw, Me)
End Using
End Sub
Private tempState As Object = Me
Public Sub ReadFromXML(ByVal inputFilename As String)
Dim xmls = New System.Xml.Serialization.XmlSerializer(Me.GetType)
Using sr As New IO.StreamReader(inputFilename)
tempState = xmls.Deserialize(sr)
End Using
For Each pi In tempState.GetType.GetProperties()
Dim name = pi.Name
' THIS IS THE PART THAT i CANT FIGURE OUT (HOW TO DO THIS WITHOUT LINQ)
Dim realProp = (From p In Me.GetType.GetProperties
Where p.Name = name And p.MemberType = Reflection.MemberTypes.Property).Take(1)(0)
' -------------------------------------------------------------
realProp.SetValue(Me, pi.GetValue(tempState, Nothing), Nothing)
Next
End Sub
End Class
答案 0 :(得分:3)
你可以用" normal"替换那个LINQ部分。 For Each
循环,例如:
Dim realProp As PropertyInfo
For Each p As PropertyInfo In Me.GetType.GetProperties()
If p.Name = Name And p.MemberType = Reflection.MemberTypes.Property Then
'set `realProp` with the first `p` that fulfil above `If` criteria'
'this is equivalent to what your LINQ (...).Take(1)(0) does'
realProp = p
Exit For
End If
Next