【问题标题】:String format template as parameter字符串格式模板作为参数
【发布时间】:2022-11-22 23:33:36
【问题描述】:
我是 C# 的初学者。现在我有下一个任务:在方法中我得到模板和参数,我必须返回格式化的字符串。
例如:
template = "Hello, {name}!"
name = "Bob"
所以结果必须是一个字符串 -> 你好,鲍勃!
public static string GetHelloGreeting(string template, string name)
{
return string.Format(template, name);
}
【问题讨论】:
标签:
c#
string
parameters
format
【解决方案1】:
template 参数的值将不得不以某种方式改变。如果你想使用字符串插值,this answer 表明了这一点。所以
template = $"Hello, {name}"; 在这种情况下,您根本不需要使用 String.Format。只需确保在定义template 之前定义name。
或者你可以像你一样使用String.Format(template, name);,但你需要template = "Hello, {0}!";
0 是将进入该位置的变量的索引。有关详细信息,请参阅String.Format
【解决方案2】:
你可以使用String.Replace:
public static string GetHelloGreeting(string template, string name)
{
return template.Replace("{name}", name);
}
【解决方案3】:
尝试这个:
string name = "Bob";
string template = $"Hello, {name}!";
Console.WriteLine(GetHelloGreeting(template, name)); // Hello, Bob!
public static string GetHelloGreeting(string template, string name)
{
return string.Format(template, name);
}
结果:
你好,鲍勃!
【解决方案4】:
在指定格式时,您可以为后面的参数使用索引。它被称为composite format string:
string template = "Hello, {0}!"
这使得它独立于变量名。但真正的原因是您正在使用的 Format 方法的重载将 params 数组作为参数,如您在方法签名中所见:
public static string Format (string format, params object?[] args);
因此模板中找到的索引将用于从传递给方法的对象数组中提取适当位置的对象