gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:53:13 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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

关于c# - 如何创建更加用户友好的 string.format 语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1322037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com