如何创建更加用户友好的string.format语法?

如何创建更加用户友好的string.format语法?,第1张

如何创建更加用户友好的string.format语法

下面的方法对匿名类型(以下示例)或常规类型(域实体等)都适用:

static void Main(){    string s = Format("You are {age} years old and your last name is {name} ",        new {age = 18, name = "Foo"});}

使用:

static readonly Regex rePattern = new Regex(    @"({+)([^}]+)(}+)", RegexOptions.Compiled);static string Format(string pattern, object template){    if (template == null) throw new ArgumentNullException();    Type type = template.GetType();    var cache = new Dictionary<string, string>();    return rePattern.Replace(pattern, match =>    {        int lCount = match.Groups[1].Value.Length, rCount = match.Groups[3].Value.Length;        if ((lCount % 2) != (rCount % 2)) throw new InvalidOperationException("Unbalanced braces");        string lBrace = lCount == 1 ? "" : new string('{', lCount / 2), rBrace = rCount == 1 ? "" : new string('}', rCount / 2);        string key = match.Groups[2].Value, value;        if(lCount % 2 == 0) { value = key;        } else { if (!cache.TryGetValue(key, out value)) {     var prop = type.GetProperty(key);     if (prop == null)     {         throw new ArgumentException("Not found: " + key, "pattern");     }     value = Convert.ToString(prop.GetValue(template, null));     cache.Add(key, value); }        }        return lBrace + value + rBrace;    });}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5044953.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存