字符串格式描述性文本

是否可以在字符串格式说明符中添加一些描述性文本?

例:

string.Format ("{0:ForeName} is not at home", person.ForeName); 

在示例中, ForeName被添加为描述。

上面的语法显然是不正确的,但只是为了表明这个想法。

我问的原因是因为在我的情况下字符串在资源文件中,所以在您目前只看到的资源文件中

  {0} is not at home 

在某些情况下,很难理解{0}的上下文是什么。

编辑:

在c#6中引入了使用$运算符的字符串插值,因此不再需要string.Format

 $"{person.ForeName} is not at home"; 

我们通常会在我们的资源文件中添加注释,例如{0} = Forename

然后,任何可能正在翻译字符串的人都知道{0}代表什么并且可以相应地进行翻译。

此外,如果您使用ReSharper,则可以在将字符串添加到资源时同时输入注释。

Phil Haack和Peli撰写了几篇关于默认string.format函数替代品的有趣博客文章。 他们可能会对你感兴趣

基本上它们允许您在格式字符串中使用对象属性,如下所示:

 string s = NamedFormat("Hello {FullName} ({EmailAdrress})!", person); 

你可以在这里找到相关的博客文章:

也许这些博客文章中涵盖的解决方案之一可以满足您的需求。

对于字符串,您的方法应该有效,因为字符串将忽略任何格式说明符。 但是,您可能会意外地将其用于非字符串类型,在这种情况下,字符串将被转换为格式代码或字面显示:

 string.Format ("{0:ForeName} is not at home", "Johnny"); //"Johnny is not at home" string.Format ("{0:ForeName} will be home at {1:HomeTime}", "Johnny", DateTime.Today) //Johnny will be home at 0o0eTi0e -- H, h, and m are DateTime format codes. 

但是,由于您将这些存储在资源文件中,我会使用资源文件中的“注释”字段 – 您可以存储格式字符串的副本并在那里添加您的描述。

没有内置的C#function。 我能提议的最好的是插入评论(这不会对性能产生影响):

 string.Format ("{0"/*ForeName*/+"} is not at home", person.ForeName); 

Personnaly,我发现它不可读,最好的方法是使用第三方工具,正如David Khaykin在评论中所建议的那样(见这个答案 )

IDEOne.com演示

这是StackOverflow的formatUnicorn方法的一些有点天真的实现:

 using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Reflection; public class Test { public static void Main() { string formatString = "{firstName} {lastName} is awesome."; Console.WriteLine(formatString.FormatUnicorn(new { firstName = "joe", lastName = "blow" })); } } public static class StringExtensions { public static string FormatUnicorn(this string str, object arguments) { string output = str; Type type = arguments.GetType(); foreach (PropertyInfo property in type.GetProperties()) { Regex regex = new Regex(@"\{" + property.Name + @"\}"); output = regex.Replace(output, property.GetValue(arguments, null).ToString()); } return output; } } 

这里最大的缺点是使用reflection,这可能很 。 另一个是它不允许格式说明符。

更好的方法可能是创建一个更复杂的正则表达式,只删除注释。

  string.Format ("{0} is not at home {1} ", person.ForeName, person.Something); 

这将打印ForeName而不是{0}和{1}中的内容。 没有办法像你说的那样。

从Visual Studio 2015开始,您可以使用Interpolated Strings (它是一个编译器技巧,因此无论您定位的.net框架的哪个版本都无关紧要)。

然后代码看起来像这样

 string txt = $"{person.ForeName} is not at home {person.Something}"; 

如果您想将字符串放入资源文件进行转换,这并不理想,但它实际上使代码更易读,更不容易出错。