如何为字符串格式提供自定义字符串占位符

26 .net c# string string-formatting

我有一个字符串

string str ="Enter {0} patient name";
Run Code Online (Sandbox Code Playgroud)

我正在使用string.format来格式化它.

String.Format(str, "Hello");
Run Code Online (Sandbox Code Playgroud)

现在,如果我想要从一些配置中检索患者,那么我需要将str改为类似的东西 "Enter {0} {1} name".所以它将用第二个值替换{1}.问题是我想要而不是{1}其他一些格式{pat}.但是当我尝试使用时,它会抛出一个错误.我想要一种不同格式的原因是我需要更改这么多文件(可能包含{0},{1}等).所以我需要一个可以在运行时替换的自定义占位符.

Mag*_*dhe 52

你可能想看看FormatWith 2.0詹姆斯·牛顿景.它允许您使用属性名称作为格式化标记,例如:

var user = new User()
{
    Name = "Olle Wobbla",
    Age = 25
};

Console.WriteLine("Your name is {Name} and your age is {Age}".FormatWith(user));
Run Code Online (Sandbox Code Playgroud)

您也可以将它与匿名类型一起使用.

更新:Scott Hanselman也有一个类似的解决方案,但它实现为一组扩展方法而不是.ObjectString

UPDATE 2012:你可以得到Calrius咨询的NETFX String.FormatWith扩展方法上的NuGet包NuGet.org

更新2014:还有StringFormat.NETlittlebit的StringFormat

  • 用于更新5年答案的+1 :-) (6认同)

Mar*_*ell 18

RegexMatchEvaluator似乎是一个不错的选择:

static readonly Regex re = new Regex(@"\{([^\}]+)\}", RegexOptions.Compiled);
static void Main()
{
    string input = "this {foo} is now {bar}.";
    StringDictionary fields = new StringDictionary();
    fields.Add("foo", "code");
    fields.Add("bar", "working");

    string output = re.Replace(input, delegate (Match match) {
        return fields[match.Groups[1].Value];
    });
    Console.WriteLine(output); // "this code is now working."
}
Run Code Online (Sandbox Code Playgroud)