C# string interpolation with variable format

后端 未结 6 1574
时光取名叫无心
时光取名叫无心 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 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)}");
    

提交回复
热议问题