如何提供自定义字符串占位符字符串格式 [英] How to provide custom string placeholder for string format

查看:145
本文介绍了如何提供自定义字符串占位符字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串

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.

推荐答案

您可能想看看<一href="http://james.newtonking.com/archive/2008/03/29/formatwith-2-0-string-formatting-with-named-variables.aspx">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.

更新:也有类似的<一个href="http://www.hanselman.com/blog/ASmarterOrPureEvilToStringWithExtensionMethods.aspx">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 和的littlebit's的StringFormat

这篇关于如何提供自定义字符串占位符字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆