将所有不同的占位符替换为类属性值

Jac*_*ost 5 c# string reflection formatting

我有一堂课如下

    public class Details
    {
        public string CreatedAt {set;get;)
        public Order Order { get; set; }
        public Customer Customer { get; set; }
     }
    public class Customer
    {
        public string Name { get; set; }
        public CustomerAddress Address { get; set; }
    }

    public class CustomerAddress
    {
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string City { get; set; }
        public string State { get; set; } 
    }

Run Code Online (Sandbox Code Playgroud)

我有 HTML 文件,其中包含 HTML 内容和几个占位符。我正在替换占位符,如下所示。


  public static string ReplaceStringPlaceHolders(User Details)
        {
                 string MyHTML= File.ReadAllText(@"...Path");
                 //Replacing one by one
                 string newstring= MyHTML.
                .Replace("{created_at}", Details.CreatedAt)
                .Replace("{customer_info.address.line_1}", Details.Customer.Address.Line1)
                .Replace("{customer_info.address.line_2}", Details.Customer.Address.Line2)
                .Replace("{customer_info.address.city}", Details.Customer.Address.City)
                .Replace("{customer_info.address.state}", Details.Customer.Address.State)
                .Replace("{customer_info.address.postal_code}", Details.Customer.Address.PostalCode)
                .Replace("{customer_info.address.country}", Details.Customer.Address.Country)
            return newstring;

        }

Run Code Online (Sandbox Code Playgroud)

但我不喜欢这种方式,因为我在 HTML 文件中放置了 50 多个占位符。当占位符名称与类属性匹配时,有没有一种方法可以替换占位符。

如果可能的话,我正在寻找这样的东西:

MyHTML.replaceifPlaceHolderMatchesWithClassProperties(Label);
Run Code Online (Sandbox Code Playgroud)

请建议。

Dmi*_*nko 2

是的,您可以借助ReflectionLinq读取属性:

using System.Linq;
using System.Reflection;

....

private static string TryReadReflectionValue(object data, string name) {
  if (name == null)
    return null;

  foreach (string item in name.Replace("_", "").Trim('{', '}').Split('.')) {
    if (data == null)
      return null;

    var prop = data
      .GetType()
      .GetProperties(BindingFlags.Instance | BindingFlags.Static | 
                     BindingFlags.Public)
      .Where(p => p.Name.Equals(item, StringComparison.OrdinalIgnoreCase))
      .Where(p => p.CanRead)
      .Where(p => p.GetIndexParameters().Length <= 0)
      .FirstOrDefault();

    if (prop == null)
      return null;

    data = prop.GetValue(prop.GetGetMethod().IsStatic ? null : data);
  }

  return data?.ToString();
}
Run Code Online (Sandbox Code Playgroud)

并借助正则表达式匹配占位符:

using System.Text.RegularExpressions;

...

private static string MyReplace(string text, object data) {
  if (text == null)
    return text;  

  return Regex.Replace(
    text,
    @"\{\w._]+\}",
    match => TryReadReflectionValue(data, match.Value) ?? match.Value);
}
Run Code Online (Sandbox Code Playgroud)

用法:

public static string ReplaceStringPlaceHolders(User Details) {
  string MyHTML= File.ReadAllText(@"...Path");

  return MyReplace(text, Details); 
}
Run Code Online (Sandbox Code Playgroud)

在这里我假设

  1. 我们总是添加 _占位符,例如{created_at}对应于CreatedAt属性
  2. 我们忽略占位符中的大小写:{created_at} == {Created_At} == {CREATED_at}等等。
  3. 所有占位符均采用{letters,digits,_,.}格式