我想从几个指定的参数生成一个
HTML表.具体来说,我想传入我的方法的两个参数是:IEnumerable列表和T的属性的一些子集.例如,假设我有一个这个类的列表:
class Person { string FirstName string MiddleName string LastName }
让我们来看看这个名单里有5个人.我想通过这样做来获得该类(或任何其他任意类)的HTML表:
List<Person> people; ...add people to list string HTML = GetMyTable(people,"FirstName","LastName");
我确定有一个更好的方法来指定哪些属性我想要从表生成表(或哪些属性我想从表中排除,这将更好,因为我通常会想要大部分或全部的类的属性),但我“我不知道(我从来没有用过反思,但我猜这是怎么回事).此外,该方法应该接受任何类型的类的列表.
关于如何实现这一点的任何聪明的想法?
解决方法
也许这样吗?
var html = GetMyTable(people,x => x.LastName,x => x.FirstName); public static string GetMyTable<T>(IEnumerable<T> list,params Func<T,object>[] fxns) { StringBuilder sb = new StringBuilder(); sb.Append("<TABLE>\n"); foreach (var item in list) { sb.Append("<TR>\n"); foreach(var fxn in fxns) { sb.Append("<TD>"); sb.Append(fxn(item)); sb.Append("</TD>"); } sb.Append("</TR>\n"); } sb.Append("</TABLE>"); return sb.ToString(); }
– 版本2.0–
public static string GetMyTable<T>(IEnumerable<T> list,params Expression<Func<T,object>>[] fxns) { StringBuilder sb = new StringBuilder(); sb.Append("<TABLE>\n"); sb.Append("<TR>\n"); foreach (var fxn in fxns) { sb.Append("<TD>"); sb.Append(GetName(fxn)); sb.Append("</TD>"); } sb.Append("</TR> <!-- HEADER -->\n"); foreach (var item in list) { sb.Append("<TR>\n"); foreach (var fxn in fxns) { sb.Append("<TD>"); sb.Append(fxn.Compile()(item)); sb.Append("</TD>"); } sb.Append("</TR>\n"); } sb.Append("</TABLE>"); return sb.ToString(); } static string GetName<T>(Expression<Func<T,object>> expr) { var member = expr.Body as MemberExpression; if (member != null) return GetName2(member); var unary = expr.Body as UnaryExpression; if (unary != null) return GetName2((MemberExpression)unary.Operand); return "?+?"; } static string GetName2(MemberExpression member) { var fieldInfo = member.Member as FieldInfo; if (fieldInfo != null) { var d = fieldInfo.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute; if (d != null) return d.Description; return fieldInfo.Name; } var propertInfo = member.Member as PropertyInfo; if (propertInfo != null) { var d = propertInfo.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute; if (d != null) return d.Description; return propertInfo.Name; } return "?-?"; }