以下是一个例子:
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Test {0, 10}", 1100);
Console.WriteLine("Test {0, 10}", 2);
Console.WriteLine("Test {0, 10}", 40);
}
}
输出结果为:
Test 1100
Test 2
Test 40
Press any key to continue . . .
是否可以在上面的示例变量中设置数字10
?
以下描述了意图,但没有编译,因为预期string
,而不是int
:
public class Program
{
public static void Main(string[] args)
{
int i = 10;
Console.WriteLine("Test {0, i}", 1100);
Console.WriteLine("Test {0, i}", 2);
Console.WriteLine("Test {0, i}", 40);
}
}
答案 0 :(得分:6)
使用C#6,您可以使用string interpolation:
Console.WriteLine($"Test {{0, {i}}}", 1100);
Console.WriteLine($"Test {{0, {i}}}", 2);
Console.WriteLine($"Test {{0, {i}}}", 40);
C#6中字符串插值的好处是它包括变量的编译时检查。为了使字符串插值工作,您需要在字符串前面加上美元符号($
)。
没有字符串插值的另一个选项是:
int i = 10;
Console.WriteLine("Test {0, " + i + "}", 1100);
Console.WriteLine("Test {0, " + i + "}", 2);
Console.WriteLine("Test {0, " + i + "}", 40);
或者:
Console.WriteLine("Test " + 1100.ToString().PadLeft(i));
Console.WriteLine("Test " + 2.ToString().PadLeft(i));
Console.WriteLine("Test " + 40.ToString().PadLeft(i));
答案 1 :(得分:3)
一个简单的解决方案是:
public class Program
{
public static void Main(string[] args)
{
int i = 10;
Console.WriteLine("Test {0, " + i + "}", 1100);
Console.WriteLine("Test {0, " + i + "}", 2);
Console.WriteLine("Test {0, " + i + "}", 40);
}
}