repeater 模拟器 in winform
2012-02-08 17:27 【当耐特】 阅读(2994) 评论(6) 编辑 收藏 举报需求
有一个这样的需求,根据给定的数据源和html模板生成html,强大的All in one code中的代码不能满足需求,所以就有了RepeaterSimulate.
其中涉及:反射、泛型、正则表达式等基础知识。
RepeaterSimulate使用
RepeaterSimulate r = new RepeaterSimulate();
r.ItemTemplate = "<div>#Name#<div><div>#Age#<div>";
List<TestModel> tm = new List<TestModel>() {
new TestModel(){Name="zhangsan",Age=11},new TestModel(){Name="lisi",Age=12},new TestModel(){Name="wangwu",Age=13},new TestModel(){Name="sunliu",Age=31}};string html = r.GenerateHTML<TestModel>(tm);
Console.WriteLine(html);Console.Read();
效果如图:
RepeaterSimulate实现
模拟器中的GenerateHTML方法:
public string GenerateHTML<T>(object obj){StringBuilder sb = new StringBuilder();
IEnumerable<T> enumerable = obj as IEnumerable<T>;
MemberInfo[] myMemberInfo;// Get the type of 'MyClass'.
Type myType = typeof(T);
// Get the information related to all public member's of 'MyClass'.
myMemberInfo = myType.GetMembers();string regexText = "#\\w{1,}#";Match mt = Regex.Match(this.ItemTemplate, regexText);
List<string> results = RegularHelper.GetResult(mt);
foreach (var item in enumerable){string tempStr = this.ItemTemplate;for (int i = 0; i < myMemberInfo.Length; i++){if (myMemberInfo[i].MemberType.ToString() == "Property"){if (results.Contains(myMemberInfo[i].Name))
{object v = myType.InvokeMember(myMemberInfo[i].Name,
BindingFlags.DeclaredOnly |BindingFlags.Public | BindingFlags.NonPublic |BindingFlags.Instance | BindingFlags.GetProperty, null, item, null);tempStr = tempStr.Replace("#" + myMemberInfo[i].Name + "#", v.ToString());}}}sb.Append(tempStr);}return sb.ToString();
}
其中的#\\w{1,}#匹配对象为”#中间为字符,字符数量大于1个#”,这里约定好被绑定的数据源的属性名在两个#之间,当然也可以类似aspx<%#神马的 %>
遍历正则匹配到的属性:
public class RegularHelper{private static List<string> Result {get;set;}public static List<string> GetResult(Match mt){List<string> r = new List<string>();GetMatchValues(mt,r);return r;
}private static void GetMatchValues(Match mt, List<string> r){r.Add(mt.Value.TrimStart('#').TrimEnd('#'));if (mt.NextMatch().Length > 0)
GetMatchValues(mt.NextMatch(),r);}}
上面的GetMatchValues递归遍历出所有匹配的对象。
思考题
支持这种写法#Name.substring(0,12)+”……”#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库