C# string interpolation with variable format

后端 未结 6 1575
时光取名叫无心
时光取名叫无心 2021-01-18 06:15

I need to format a variable with string interpolation, and the format string is another variable:

here is my sample code:

static void Main(string[] a         


        
相关标签:
6条回答
  • 2021-01-18 06:55

    Your code is equivalent to:

    Console.WriteLine(String.Format("Test 2: {0:formatString}", i));
    

    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.

    0 讨论(0)
  • 2021-01-18 06:59

    C# has no syntax that will do what you want.

    0 讨论(0)
  • 2021-01-18 07:00

    The string interpolation happens in the compilation stage. You cannot use variables in the format strings because of that.

    0 讨论(0)
  • 2021-01-18 07:05

    You can make a simple extension method that allows you to call a formattable ToString method on any object. The IFormattable interface is the same way that string.Format or interpolated strings would use to format an object of unknown type.

    public static string ToString(this object value, string format, IFormatProvider provider = null)
        => (value as IFormattable)?.ToString(format, provider) ?? value.ToString();
    

    And to use:

    object i = 12345;
    var formatString = "N5";
    
    Console.WriteLine($"Test 2: {i.ToString(formatString)}");
    
    0 讨论(0)
  • 2021-01-18 07:11

    I have tested this piece of code and it seems to work:

    static void Main(string[] args)
    {
        int i = 12345;
    
        Console.WriteLine("Test 1: {0:N5}",i);
    
        var formatString = "N5";
    
        Console.WriteLine("Test 2: {0:" + formatString + "}", i);
    
        Console.ReadLine();
    }
    
    0 讨论(0)
  • 2021-01-18 07:14

    The shortest way you can do this 'syntactically' without String.Format, is using ToString:

    $"Test 2: {i.ToString(formatString)}"
    
    0 讨论(0)
提交回复
热议问题