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

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

    Well, it's more complicated than it looks. Others say this is possible, and I don't doubt them, but it doesn't seem to be the case in Mono.

    There, the standard overloads of the Format() method seem to take precedence in the name resolution process, and compilation fails because a static method ends up being called on an object instance, which is illegal.

    Given this code:

    public static class Extensions
    {
        public static string Format(this string str, params object[] args)
        {
            return String.Format(str, args);
        }
    }
    
    class Program
    {
        public static void Main()
        {
            Console.WriteLine("string goes here {0} {1}".Format("foo", "bar"));
        }
    }
    

    The Mono compiler (mcs 2.10.2.0) replies with:

    foo.cs(15,54): error CS0176: Static member `string.Format(string, object)' cannot be accessed with an instance reference, qualify it with a type name instead

    Of course, the above compiles cleanly if the extension method is not named Format(), but maybe you actually want to use that name. If that's the case, then it's not possible, or at least not on all implementations of the .NET platform.

提交回复
热议问题