【发布时间】:2021-08-24 15:37:36
【问题描述】:
static void BuildStrings(List<string> sentences)
{
string name = "Tom";
foreach (var sentence in sentences)
Console.WriteLine(String.Format(sentence, name));
}
static void Main(string[] args)
{
List<string> sentences = new List<string>();
sentences.Add("Hallo {0}\n");
sentences.Add("{0[0]} is the first Letter of {0}\n");
BuildStrings(sentences);
Console.ReadLine();
}
//Expected:
//Hallo Tom
//T is the first Letter of Tom
但我得到了:
System.FormatException: '输入字符串的格式不正确。'
如何在不改变BuildStrings方法的情况下得到“Tom”的第一个字母?
【问题讨论】:
-
这是不可能的,不。
-
绝对不是开箱即用的,但是您可以使用
FormatWith()构建类似的东西并获得类似"{name:left:1}"的东西,然后通过创建自己的处理程序重载使用"{name:left:1}".FormatWith(new { name })调用它。