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

2023-09-03 09:14:01 作者:枕上诗书闲

我有一个字符串

string str ="Enter {0} patient name";

我使用的String.Format格式化。

I am using string.format to format it.

String.Format(str, "Hello");

现在,如果我想病人也从一些配置,然后我需要改变海峡喜欢的东西检索 输入{0} {1}的名字。因此,它将取代{1}用第二个值。问题是,我想,而不是{1}的其他格式类似 {拍拍} 。但是,当我尝试使用,它抛出一个错误。我希望有一个不同的格式的原因是,有很多我需要改变这样的文件(可能含有{0},{1}等)。所以我需要一个自定义的占位符,可以在运行时进行更换。

Now if i want patient also to be retrieved from some config then I need to change str to something like "Enter {0} {1} name". So it will replace the {1} with second value. The problem is that I want instead of {1} some other format something like {pat}. But when I try to use, it throws an error. The reason I want a different format is that there are lot of files I need to change like this(which may contain {0},{1} etc). So I need a custom placeholder which can be replaced at run-time.

推荐答案

您可能想看看FormatWith 2.0 通过詹姆斯·牛顿 - 王。它允许您使用属性名称作为格式的标记,如这样的:

You might want to check out FormatWith 2.0 by James Newton-King. It allows you to use property names as formatting tokens such as this:

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

Console.WriteLine("Your name is {Name} and your age is {Age}".FormatWith(user));

您也可以使用它与匿名类型。

You can also use it with anonymous types.

更新:也有类似的solution通过在Scott Hanselman 但它,而不是作为一组扩展方法对对象对字符串

UPDATE: There is also a similar solution by Scott Hanselman but it is implemented as a set of extension methods on Object instead of String.

更新2012 :您可以Calrius咨询的 NETFX String.FormatWith扩展方法的NuGet包在 NuGet.org

UPDATE 2012: You can get Calrius Consulting's NETFx String.FormatWith Extension Method NuGet package on NuGet.org

更新2014年:还有 StringFormat.NET 和的