首页 > 解决方案 > 将带有命名参数的字符串模板格式化为文字 c#

问题描述

我有一个使用命名变量创建字符串模板的应用程序。这是根据ASP.NET Core的日志记录指南完成的

现在我发现自己也想通过 API 本身传递这些字符串,但这次是填写了所有参数。

基本上我想使用:

var template = "ID {ID} not found";
var para = new object[] {"value"};
String.Format(template, para);

但是,这会给出无效的输入字符串。当然,我也不能保证有人不会将字符串模板制作成带有索引的“经典”方式。

var template2 = "ID {0} not found";

有没有一种我缺少的格式化字符串的新方法,或者我们应该解决这个问题?

我不想修改现有代码库以使用数字或使用 $"...{para}" 语法。因为这会在记录时丢失信息。

我猜我可以进行正则表达式搜索,看看是否有“{0}”或命名参数,并在格式化之前用索引替换命名。但我想知道是否有一些更简单/更清洁的方法来做到这一点。

更新 - 正则表达式解决方案:

贝娄是我使用正则表达式所做的当前解决方法

public static class StringUtils
    {
        public static string Format(string template, params object[] para)
        {
            var match = Regex.Match(template, @"\{@?\w+}");
            if (!match.Success) return template;

            if (int.TryParse(match.Value.Substring(1, match.Value.Length - 2), out int n))
                return string.Format(template, para);
            else
            {
                var list = new List<string>();
                var nextStartIndex = 0;
                var i = 0;
                while (match.Success)
                {
                    if (match.Index > nextStartIndex)
                        list.Add(template.Substring(nextStartIndex , match.Index - nextStartIndex) + $"{{{i}}}");
                    else
                        list.Add($"{{{i}}}");

                    nextStartIndex = match.Index + match.Value.Length;

                    match = match.NextMatch();
                    i++;
                }

                return string.Format(string.Join("",list.ToArray()), para);
            }
        }
    }

标签: c#asp.net-corestring.formatstringtemplate

解决方案


推荐阅读