本文介绍了C#中的字符串插补可变格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要格式化字符串插一个变量,格式字符串是另一个变量:
I need to format a variable with string interpolation, and the format string is another variable:
下面是我的示例代码:
static void Main(string[] args) { int i = 12345; Console.WriteLine($"Test 1: {i:N5}"); var formatString = "N5"; Console.WriteLine($"Test 2: {i:formatString}"); }
1的测试工作,测试2不工作。
Test 1 works, Test 2 don't work.
什么是用于测试2的确切语法
What's the exact syntax for Test 2 ?
推荐答案您的代码等同于:
Your code is equivalent to:
Console.WriteLine(String.Format("Test 2: {0:formatString}", i));
由于的formatString 是格式字符串,你要嵌套的String.Format 要求把数值格式字符串:
As the formatString is in the format string, you would nest String.Format calls to put the value in the format string:
Console.WriteLine(String.Format(String.Format("Test 2: {{0:{0}}}", formatstring), i));这是不支持用绳子插值。
This isn't supported with string interpolation.
更多推荐
C#中的字符串插补可变格式
发布评论