如何创建更加用户友好的string.format语法? [英] How can I create a more user-friendly string.format syntax?

查看:69
本文介绍了如何创建更加用户友好的string.format语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在程序中创建一个很长的字符串,并且一直在使用String.Format。当您拥有8-10个以上的参数时,我面临的问题是跟踪所有数字。

I need to create a very long string in a program, and have been using String.Format. The problem I am facing is keeping track of all the numbers when you have more than 8-10 parameters.

是否可以创建某种形式的重载以接受与此类似的语法?

Is it possible to create some form of overload that will accept a syntax similar to this?

String.Format("You are {age} years old and your last name is {name} ",
{age = "18", name = "Foo"});


推荐答案

以下内容如何适用于匿名类型(下面的示例)或常规类型(域实体等):

How about the following, which works both for anonymous types (the example below), or regular types (domain entities, etc):

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;
    });
}

这篇关于如何创建更加用户友好的string.format语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆