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

后端 未结 9 1066
青春惊慌失措
青春惊慌失措 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:06

    Yes, you can. You'd always want to verify source is not null, of course, left that out for brevity. [Update] turns out even though you can mimic string.Format's overloads for 1, 2, and 3 args, behind the scenes the string.Format() overloads for 1, 2, and 3 args use the varg list overload anyway... So removed the overloads.

    public static class FormatExtension
    {
        public static string Format(this string source, params object[] args)
        {
            return string.Format(source, args);
        }
    }
    

    As an aside, while we show that this is possible, be careful what you extend. The main thing here is that .Format() really only has meaning on strings that have format parameters. This makes it much clearer to use string.Format() instead because then the arguments are obviously things Format() wants and should be in the correct form. Having .Format() as an extension method, though, can lose some meaning since it will appear on any string regardless of whether formatting is truly valid on it or not. Just a minor point though.

提交回复
热议问题