Adding an extension method to the string class - C#

江枫思渺然 提交于 2019-12-03 02:10:34

You're trying to call it on the type string. You need to call it on a string instance, e.g.

"{0}".SafeFormat("Hello");

Admittedly that won't do what you want it to, because the SafeFormat method is actually completely ignoring the first parameter (s) anyway. It should look like this:

    public static string SafeFormat(this string fmt, params object[] args)
    {
        string formattedString = fmt;

        try
        {
            formattedString = String.Format(fmt, args);
        }
        catch (FormatException) {} //logging string arguments were not correct
        return formattedString;
    }

Then you can call:

"{0} {1}".SafeFormat("Hi", "there");

The point of extension methods is that they look like instance methods on the extended type. You can't create extension methods which appear to be static methods on the extended type.

You're defining an instance extension method, and then trying to use it as a static method. (C# is not capable of defining a static extension method, though F# is for that matter.)

Instead of:

result = string.SafeFormat("Hello");

you want something like:

result = "Hello".SafeFormat();

i.e. You're operating on the string instance ("Hello" in this case).

Extension methods appear on instances of a type, not the type itself (e.g. static members).

try

"Hello".SafeFormat("{0} {1}", "two", "words")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!