一、前言
类似如下字符串
"ID", "NameValue", "CodeValue", "ExchangeTypeValue", 6, "invalid"
"ID2", "NameValue2", "CodeValue2", "ExchangeTypeValue2", 6, "invalid"
.......
有可能是文件中存在的,或者调用其他程序返回的结构化数 据,那么该如何解析?当其他场景中,只是返回顺序(属性顺序)变了,类结构还是一样,又如何应对?当有 很多类似场景时,是不是该抽象出一个泛型方法来应对该场景?当然,也不仅仅于上述情况,可能返回的结构 是确定,只是形式不一样,这个过程这里暂时省略,因为正则表达式完全能够解析出来。要用以下的方法,必 须转换成IEnumerable<IEnumerable<string>>结构, IEnumerable<IEnumerable<string>>结构中IEnumerable<string>为一个对象所有的值, 总体是多个对象的值集合。本文中用反射写的(关于IL操作的后续文章提供),相关的类图如下:
二、ResultTransfer的具体实现
ResultTransfer主要用于对 IEnumerable<IEnumerable<string>>结构的解析,另外还可以指定params string[] propertyNames属性参数列表来确定解析顺序(也即是属性顺序),主要方法如下:
public static IList<T> Parse<T>(IEnumerable<IEnumerable<string>> entityRows, params string[] propertyNames) where T : new()
第一个参数 entityRows为对象列表值集合。
第二个参数propertyNames为可选参数,输入该参数 后,如果propertyNames中存在相关属性,则按照propertyNames对应的属性顺序进行解析。否则按照提供的T 类中属性的DataMemberAttribute来确定属性顺序进行解析。