字符串格式化程序可以用变量参数化吗?

Can the string formatter be parametrized with variables?

例子

这是一个例子:

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);
    }
}

一个简单的解决方案是:

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);
    }
}

对于 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));