扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
Class clsA/B Property Name1 as string ... End Property Property Name2 as string ... End Property ...... ...... ...... End Class |
Public Class clscolA/B Inherits System.Collections.CollectionBase Public Function GenerateAson() As clsA/clsB 'New并返回一个 clsA or clsB '初始化属性的工作可以在这里进行 End Function Public Sub AddSon(ByVal objSon As clsA/clsB) '增加一条新纪录 InnerList.Add(objSon) End Sub Public Sub Sort() '根据某设定的属性对集合进行排序 InnerList.Sort(New clsSortByName) End Sub '默认Item属性以及更多Method从略 End Class |
With NodeList for i as integer=0 to .Count-1 Dim objson as clsA/B=colA/B.GenerateAson objson.Name1=.item(i).childnodes(x1).innertext objson.Name2=.item(i).childnodes(x2).innertext ...... ...... ...... colA/B.Addson(objson) next i End With |
Public Shared Function FillFromXml(ByVal NodeName As String, ByVal strPath As String, ByVal objFather As Object) As Boolean Try With xmlGetList(NodeName, strPath) For i As Integer = 0 To .Count - 1 Dim st As Object = objFather.GenerateAson Dim ty As Type = st.GetType For Each pp As PropertyInfo In ty.GetProperties With DirectCast(.Item(i), XmlElement) If .SelectSingleNode(pp.Name.ToUpper) IsNot Nothing Then pp.SetValue(st, CType(.SelectSingleNode(pp.Name.ToUpper).InnerText.Trim, String), Nothing) End If End With Next objFather.AddSon(st) Next End With Return True Catch ex As Exception Return False End Try End Function |
你也可能抱怨我上面的百分数计算太不科学,要算也应该拿全部来算,那就不妙了,好吧,看来也只能拿十分“老的““成熟“的来开刀了,下面便是削减代码二期工程,我们的目标是让成熟变干练,太过成熟的确不合某些同志的胃口。对应于AB两文件的类clsA/B,分别至少有30和15个属性,还好,也不过就一二百行代码就搞定,更简单点就用自己写的代码生成器,一次性生成所有属性,并不会很麻烦。不过还是有更好(准确使更精简)的解决办法,用一个通用类,十分之一的代码(实际应用中会更少)就可以做到。
这其实不过是一个继承了字典的子类,如下:
Public Class clsCommon Inherits System.Collections.DictionaryBase Public Sub AddField(ByVal FieldName As String, ByVal value As Object) Dictionary.Add(FieldName, value) End Sub Default Public Property Item(ByVal key As String) As Object Get Return Dictionary.Item(key) End Get Set(ByVal value As Object) Dictionary.Item(key) = value End Set End Property End Class |
Public Class clscolCommon Inherits System.Collections.CollectionBase Public Function GenerateAson() As clsCommon End Function Public Sub AddSon(ByVal objSon As clsCommon) End Sub Public Sub Sort() End Sub '默认Item属性以及更多Method从略 End Class |
With xmlGetList(NodeName, strPath) For i As Integer = 0 To .Count - 1 Dim st As Object = objFather.GenerateAson With DirectCast(.Item(i), XmlElement) For Each ch As XmlNode In .ChildNodes St.AddField(ch.Name,ch.InnerText) Next End With objFather.AddSon(st) Next End With |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。