【问题标题】:How to create an interpolated string from a string? [duplicate]如何从字符串创建插值字符串? [复制]
【发布时间】:2019-05-20 14:50:09
【问题描述】:

我正在开发一个从数据库中获取模板,然后以编程方式填充值的系统:

//using System.Runtime.CompilerServices;

var template = "Hello {0}"; // this string comes from the database
var name = "Joe";
var message = FormattableStringFactory.Create(template, new object[] { name });
Console.WriteLine(message);

此代码示例有效,但我只能使用数字表示法。我想以插值字符串格式将模板存储在数据库中,如下所示:

var template = "Hello {name}";

这会引发Run-time exception (line __): Input string was not in a correct format.

是否可以从字符串创建插值字符串?

【问题讨论】:

  • 字符串插值只是语法糖。我不确定您的需求,但是您是否考虑过这种情况? 1.) 知道模板中有哪些标记/占位符; 2.) 将templatefound tokensDictionary<Token, TokenValue> 中打包的数据传递到工厂 3.) 遍历找到的令牌并替换占位符 template.Replace(tokenItem, tokensData[tokenItem].Value)
  • 两种方法在人工编辑方面存在相同的问题:如果是多个索引,那么人工可能会搞砸数字;如果是name,那么人类可能会搞砸字母并将其输入为nmae。我会继续使用旧好的 {0} 并将长的拆分成几个更简单的,例如而不是“早上好{0},你愿意做{1}吗?”我会说两句话。而且,好吧,即使使用{0},你仍然可以搞砸。

标签: c#


【解决方案1】:

我以一种(可能)奇怪的方式做了类似的事情......但它确实有效,所以我尝试与你分享我的结论:

public static string ExtendedStringFormat(this string source, List<Tuple<string, string>> values)
    {
        string returnvalue = source;
        foreach(Tuple<string, string> my_touple in values)
        {
            returnvalue = returnvalue.Replace(string.Concat('{', my_touple.Item1, '}'), my_touple.Item2);
        }
        return returnvalue;
    }

你可以这样称呼它:

            List<Tuple<string, string>> lst =  new List<Tuple<string,string>>();
            lst.Add(new Tuple<string, string>("test","YAYYYYYY"));
            lst.Add(new Tuple<string, string>("test2","YAYYYYYY22222222"));
            string ret = "hem... hi? {test}, {test2}";
            ret = ret.ExtendedStringFormat(lst);

【讨论】:

  • 当前实现使用 string.Replace,这是我们试图避免的。
  • 好的,很抱歉我的回答对你没有帮助:(顺便说一句,你不喜欢 string.Replace() 的东西吗?mutch 的速度和内存效率有那么多替代方案吗?
猜你喜欢
  • 2011-08-08
  • 1970-01-01
  • 2012-01-11
  • 1970-01-01
  • 2015-05-28
  • 1970-01-01
  • 2020-03-27
  • 2014-06-27
  • 2019-02-05
相关资源
最近更新 更多