首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何创建更加用户友好的string.format语法?

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

Stack Overflow用户
提问于 2009-08-24 12:21:25
回答 6查看 4.2K关注 0票数 45

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

有没有可能创建某种形式的重载来接受类似如下的语法?

代码语言:javascript
运行
复制
String.Format("You are {age} years old and your last name is {name} ",
{age = "18", name = "Foo"});
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2009-08-24 12:33:23

下面的代码如何,它既适用于匿名类型(下面的示例),也适用于常规类型(域实体等):

代码语言:javascript
运行
复制
static void Main()
{
    string s = Format("You are {age} years old and your last name is {name} ",
        new {age = 18, name = "Foo"});
}

使用:

代码语言:javascript
运行
复制
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;
    });
}
票数 71
EN

Stack Overflow用户

发布于 2015-10-07 19:31:09

从C#6开始,现在可以使用新的string interpolation语法进行这种字符串插值:

代码语言:javascript
运行
复制
var formatted = $"You are {age} years old and your last name is {name}";
票数 4
EN

Stack Overflow用户

发布于 2009-08-24 12:25:12

不是完全相同,但有点欺骗它。使用扩展方法、字典和一些代码:

就像这样..。

代码语言:javascript
运行
复制
  public static class Extensions {

        public static string FormatX(this string format, params KeyValuePair<string, object> []  values) {
            string res = format;
            foreach (KeyValuePair<string, object> kvp in values) {
                res = res.Replace(string.Format("{0}", kvp.Key), kvp.Value.ToString());
            }
            return res;
        }

    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1322037

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档