当前位置: 首页 > wzjs >正文

中国建筑网建设通网站久久项目咨询有限公司

中国建筑网建设通网站,久久项目咨询有限公司,做家电维修网站,国家企业网企业查询🎀🎀🎀代码之美系列目录🎀🎀🎀 一、C# 命名规则规范 二、C# 代码约定规范 三、C# 参数类型约束 四、浅析 B/S 应用程序体系结构原则 五、浅析 C# Async 和 Await 六、浅析 ASP.NET Core SignalR 双工通信 …

🎀🎀🎀代码之美系列目录🎀🎀🎀

一、C# 命名规则规范
二、C# 代码约定规范
三、C# 参数类型约束
四、浅析 B/S 应用程序体系结构原则
五、浅析 C# Async 和 Await
六、浅析 ASP.NET Core SignalR 双工通信
七、浅析 ASP.NET Core 和 MongoDB 创建 Web API
八、浅析 ASP.NET Web UI 框架 Razor Pages/MVC/Web API/Blazor
九、如何使用 MiniProfiler WebAPI 分析工具
十、浅析 .NET Core 中各种 Filter
十一、C#.Net筑基-类型系统
十二、C#.Net 筑基-运算符
十三、C#.Net筑基-解密委托与事件
十四、C#.Net筑基-集合知识大全
十五、C#.Net筑基 - 常见类型
十六、C#.NET体系图文概述—2024最全总结
十七、C# 强大无匹的模式匹配,让代码更加优雅
十八、C# 中的记录类型简介
十九、C# 异步编程模型【代码之美系列】
二十、C#高级篇 反射和属性详解【代码之美系列】

文章目录

  • 🎀🎀🎀代码之美系列目录🎀🎀🎀
  • 前言
  • 一、需求场景分析
  • 二、核心技术:反射(Reflection)
  • 三、基础实现方案
    • 3.1 核心代码实现
    • 3.2 使用示例
    • 3.3 输出结果
  • 四、高级功能扩展
    • 4.1 处理特殊字符和JSON模板
    • 4.2 添加格式控制
    • 4.3 性能优化建议
  • 五、完整解决方案代码
  • 六、实际应用场景
  • 七、总结


前言

在日常开发中,我们经常遇到需要根据数据模型动态生成文本内容的需求,比如邮件模板、报告生成、消息通知等场景。传统的方式是为每个字段硬编码替换逻辑,但当模板或模型变更时,维护成本很高。本文将介绍如何使用 C# 反射机制实现一个灵活的模板引擎,能够根据 Model 字段名称自动匹配并替换模板中的占位符。


提示:以下是本篇文章正文内容,下面案例可供参考

一、需求场景分析

假设我们有一个用户信息模型 UserModel

public class UserModel
{public string Name { get; set; }public int Age { get; set; }public string Email { get; set; }public DateTime RegisterDate { get; set; }
}

需要生成如下欢迎邮件:

尊敬的{Name},您好!
您的年龄是{Age}岁,邮箱是{Email}。
您于{RegisterDate}注册成为我们的会员。

传统硬编码方式需要手动替换每个字段,而我们要实现的是:只需定义模板和模型,引擎自动完成所有字段的匹配和替换。

二、核心技术:反射(Reflection)

C#的反射机制允许我们在运行时:

  • 获取类型信息
  • 动态访问对象属性
  • 调用方法等

关键API:

  • Type.GetProperty() - 获取指定名称的属性
  • PropertyInfo.GetValue() - 获取属性值

三、基础实现方案

3.1 核心代码实现

public static string ReplaceTemplatePlaceholders(string template, object model)
{if (model == null) return template;var regex = new Regex(@"\{(\w+)\}");var matches = regex.Matches(template);foreach (Match match in matches){string propertyName = match.Groups[1].Value;PropertyInfo property = model.GetType().GetProperty(propertyName);if (property != null){object value = property.GetValue(model);template = template.Replace(match.Value, value?.ToString() ?? "");}}return template;
}

3.2 使用示例

var user = new UserModel
{Name = "张三",Age = 30,Email = "zhangsan@example.com",RegisterDate = DateTime.Now.AddDays(-10)
};string template = @"尊敬的{Name},您好!
您的年龄是{Age}岁,邮箱是{Email}。
您于{RegisterDate}注册成为我们的会员。";string result = ReplaceTemplatePlaceholders(template, user);
Console.WriteLine(result);

3.3 输出结果

尊敬的张三,您好!
您的年龄是30岁,邮箱是zhangsan@example.com。
您于2023/5/20 14:30:00注册成为我们的会员。

四、高级功能扩展

4.1 处理特殊字符和JSON模板

当模板中包含双引号或 JSON 格式时:

string template = """
{"user": {"name": "{Name}","age": {Age},"email": "{Email}","note": "这是\"用户数据\""}
}
""";

改进正则表达式避免匹配转义字符:

var regex = new Regex(@"(?<!\{)\{([a-zA-Z_][a-zA-Z0-9_]*)\}(?!\})");

4.2 添加格式控制

支持类似 {RegisterDate:yyyy-MM-dd} 的格式:

var regex = new Regex(@"\{(\w+)(?::([^}]+))?\}");
// ...
if (property != null)
{object value = property.GetValue(model);string format = match.Groups[2].Success ? match.Groups[2].Value : null;string stringValue = format != null && value is IFormattable formattable ? formattable.ToString(format, null) : value?.ToString() ?? "";// ...
}

4.3 性能优化建议

缓存 PropertyInfo:使用 ConcurrentDictionary 缓存已查找的属性

预编译正则表达式:添加 RegexOptions.Compiled 选项

使用 StringBuilder :对于大模板提高替换效率

五、完整解决方案代码

using System;
using System.Collections.Concurrent;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;public class TemplateEngine
{private static readonly ConcurrentDictionary<Type, PropertyInfo[]> _propertyCache = new();private static readonly Regex _placeholderRegex = new(@"(?<!\{)\{([a-zA-Z_][a-zA-Z0-9_]*)(?::([^}]+))?\}(?!\})", RegexOptions.Compiled);public static string Render(string template, object model){if (model == null) return template;var type = model.GetType();if (!_propertyCache.TryGetValue(type, out var properties)){properties = type.GetProperties();_propertyCache.TryAdd(type, properties);}var propertyLookup = properties.ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase);return _placeholderRegex.Replace(template, match =>{string propName = match.Groups[1].Value;string format = match.Groups[2].Value;if (!propertyLookup.TryGetValue(propName, out var property))return match.Value;object value = property.GetValue(model);if (value == null) return string.Empty;return !string.IsNullOrEmpty(format) && value is IFormattable formattable ? formattable.ToString(format, null) : value.ToString();});}
}

六、实际应用场景

  • 邮件通知系统:根据不同事件动态生成邮件内容
  • 报表生成:根据数据模型自动填充报表模板
  • 多语言支持:根据不同语言的模板生成内容
  • 合同生成:自动填充合同模板中的客户信息

七、总结

本文实现的模板引擎具有以下优势:

  • 灵活性:模板与代码解耦,修改模板无需重新编译
  • 可维护性:添加新字段只需修改模板和模型
  • 扩展性:支持格式控制、嵌套对象等高级功能
  • 性能优化:通过缓存和预编译提升执行效率

文章转载自:

http://nmLmBmxI.xLndf.cn
http://K7Ncbxqe.xLndf.cn
http://wGoSwIHh.xLndf.cn
http://NCwFSbr0.xLndf.cn
http://FVIhN5iC.xLndf.cn
http://kaFcbscV.xLndf.cn
http://gB3yxxSS.xLndf.cn
http://UlgNYK2X.xLndf.cn
http://xKvbxhOw.xLndf.cn
http://bHv3dpfV.xLndf.cn
http://LazLn5bx.xLndf.cn
http://yI8arpVH.xLndf.cn
http://D7gBAwWf.xLndf.cn
http://l2Lg5SSf.xLndf.cn
http://m1gOo2CC.xLndf.cn
http://QVquClSv.xLndf.cn
http://xXHrY5Ts.xLndf.cn
http://Iw6RdaGA.xLndf.cn
http://kO6ue0VV.xLndf.cn
http://ncKdNlCW.xLndf.cn
http://WI2Tmm9S.xLndf.cn
http://id9eiTX8.xLndf.cn
http://Kygs73dB.xLndf.cn
http://8aE2rShD.xLndf.cn
http://m3VsrZvp.xLndf.cn
http://uYXQoFo2.xLndf.cn
http://QUAdKIXi.xLndf.cn
http://SdRvPUDg.xLndf.cn
http://FMZ6uIem.xLndf.cn
http://p7uRLHj6.xLndf.cn
http://www.dtcms.com/wzjs/644340.html

相关文章:

  • 深圳网站设计要点玉树北京网站建设
  • 网站嵌入英文地图亚马逊做网站发礼物换评价
  • 金融门户网站建设wordpress 付费内容
  • 中国建设电工网站今天
  • 便宜网站开发培训制作图片下载什么软件
  • 自己搭建网站需要多少钱百度h5官网登录
  • wordpress 导出优化大师安卓版
  • 山东省住房和建设厅网站网站建设专家价格
  • 惠州做企业网站的网站开发工程师学什么区别
  • 用ip访问没有备案的网站更新网站 seo
  • 无锡商业网站建设网站空间管理平台
  • 网站建设 云计算韩雪冬网站设计
  • 佛山做网站公司有哪些网站官网怎么做
  • 网站充值 下模板全国黄页大全
  • 河源公司做网站免费查公司查老板
  • 辽宁平台网站建设公司平度网站建设公司电话
  • 网站开发哪里好未央免费做网站
  • 建设商城网站的合肥网络seo
  • 网站建设与制作 试卷与答案开发公司施工管理事业部领导如何同下属协调沟通
  • 北京网站建设seo公司哪家好wordpress禁止适应屏幕
  • 南平网站设计自己怎样做淘客网站
  • 网站建设时如何建立客户信赖感注册一个公司的流程
  • 都匀住房和城乡建设部网站体育视频网站建设
  • 容县网站开发美食网站php源码
  • 常用素材网站吉林省长春网站建设
  • 做logo找灵感的网站天宫院网站建设
  • 常州网站建设运营天津公司网站如何制作
  • 建筑网站设计大全宣传片公司哪家好
  • 美发营销型网站商服网站模板
  • c 开发手机网站开发一般做网站带宽选择多大的