开发者

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

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

开发者_JS百科 string.Format("string goes here with placeholders like {0} {1}", firstName, lastName);

Now, is it possible to create an extension method to do it this way?

 "string goes here {0} {1}".Format(firstName, lastName);

That's all.


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.


Yes it is possible:

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

It would be good to add overloads for cases of one and two arguments.

Overall however, I don't see much value to this.


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.


You should always pass an IFormatProvider to String.Format, such as CultureInfo.InvariantCulture.

I like to use this set of extension methods:

public static class GlobalizedFormatting
{
    public static string Format(this string format, IFormatProvider provider, params object[] args)
    {
        return String.Format(provider, format, args);
    }

    public static string FormatInvariant(this string format, params object[] args)
    {
        return String.Format(CultureInfo.InvariantCulture, format, args);
    }

    public static string FormatCurrent(this string format, params object[] args)
    {
        return String.Format(CultureInfo.CurrentCulture, format, args);
    }
}

Usage:

"{0} {1} {2}".Format(CultureInfo.InvariantCulture, "A", "B", "C");

"{0} {1} {2}".FormatInvariant("A", "B", "C");

"{0} {1} {2}".FormatCurrent("A", "B", "C");


sure...

public static class StringExtensions
{
    public static string FormatThis(this string format, params object[] args)
    {
        return string.Format(format, args);
    }
}


Yes.       

public static string Format(this string str, string firstItem, string secondItem)
{
    return string.Format(str, firstItem, secondItem);
}

BTW, this method has to belong to a public and static class.


("string goes here {0} {1}").Format(firstName, lastName);

Yes you can. But what the purpose it will solve?


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"));


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

$"string goes here {firstName} {lastName}";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜