You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 替换字符串中插值占位符为类对应属性值的实现方法

方案1:修正SmartFormat实现

Smart.Format 方法需要传入数据源对象才能解析占位符对应的属性值,未传入当前Mail实例时会无法定位到name属性。
修正后代码:

void FormatHeader(){
    header = Smart.Format(header, this);
}
方案2:修正反射实现

原实现存在三个问题:

  • Mail类的name、header属性默认是私有访问级别,GetProperty默认仅查询公共(public)属性,需要额外指定查询范围
  • 直接拼接GetProperty返回的PropertyInfo对象,没有调用GetValue获取实际的属性值
  • 循环中直接修改原header字符串会导致后续匹配的索引错位,推荐使用Regex.Replace的匹配回调实现
    修正后代码:
using System.Reflection;
using System.Text.RegularExpressions;

void FormatHeader(){
    header = Regex.Replace(header, @"{(.*?)}", match =>
    {
        string propName = match.Groups[1].Value;
        PropertyInfo prop = GetType().GetProperty(propName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
        if (prop == null) return match.Value; // 找不到属性则保留原占位符
        return prop.GetValue(this)?.ToString() ?? string.Empty;
    });
}

如果不想用BindingFlags参数,也可以直接将Mail类的属性访问修饰符改为public:

public string header {get;set;}
public string name {get;set;}

内容的提问来源于stack exchange,提问作者Foxhunt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:36:03