Is it possible to create an extension method to format a string?

后端 未结 9 1065
青春惊慌失措
青春惊慌失措 2021-01-12 00:56

the question is really simple. How do we format strings in C#? this way:

 string.Format(\"string goes here with placeholders like {0} {1}\", firstName, lastN         


        
相关标签:
9条回答
  • 2021-01-12 01:20

    Yes it is possible:

    public static class Extensions
    {
        public static string Format(this string str, params object[] args)
        {
            return String.Format(str, args);
        }
    }
    

    and should using as below:

    Console.WriteLine("format string {0} {1}".Format((object)"foo", "bar"));
    
    0 讨论(0)
  • 2021-01-12 01:21

    Yes as everybody above has said. But the newly preferred way should be:

    $"string goes here {firstName} {lastName}";
    
    0 讨论(0)
  • 2021-01-12 01:23

    sure...

    public static class StringExtensions
    {
        public static string FormatThis(this string format, params object[] args)
        {
            return string.Format(format, args);
        }
    }
    
    0 讨论(0)
提交回复
热议问题