在C#中向字符串类添加扩展方法

18

不确定我在这里做错了什么。该扩展方法未被识别。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using StringExtensions;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            RunTests();
        }

        static void RunTests()
        {
            try
            {
                ///SafeFormat
                SafeFormat("Hi There");

                SafeFormat("test {0}", "value");

                SafeFormat("test missing second value {0} - {1}", "test1");

                SafeFormat("{0}");

                //regular format
                RegularFormat("Hi There");

                RegularFormat("test {0}", "value");

                RegularFormat("test missing second value {0} - {1}", "test1");

                RegularFormat("{0}");

                ///Fails to recognize the extension method here
                string.SafeFormat("Hello");

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.ReadLine();
        }

        private static void RegularFormat(string fmt, params object[] args)
        {
            Console.WriteLine(String.Format(fmt, args));
        }

        private static void SafeFormat(string fmt, params object[] args)
        {
            string errorString = fmt;

            try
            {
                errorString = String.Format(fmt, args);
            }
            catch (System.FormatException) { } //logging string arguments were not correct
            Console.WriteLine(errorString);
        }

    }

}

namespace StringExtensions
{
    public static class StringExtensionsClass
    {
        public static string SafeFormat(this string s, string fmt, params object[] args)
        {
            string formattedString = fmt;

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

37

您试图在 type 字符串上调用它。您需要在字符串实例上调用它,例如:

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

诚然,那样做并不能达到你想要的效果,因为SafeFormat方法实际上完全忽略了第一个参数 (s)。它应该像这样:

    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;
    }

然后您可以调用:

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

扩展方法的意义在于它们看起来像是扩展类型上的实例方法。您不能创建看起来像扩展类型上的静态方法的扩展方法。


10

你正在定义一个实例扩展方法,然后试图将其用作静态方法。(C#无法定义静态扩展方法,尽管F #可以做到。)

而应该使用:

result = string.SafeFormat("Hello");

你需要类似于以下代码:

result = "Hello".SafeFormat();
即你正在操作字符串实例(在本例中为“Hello”)。

4

扩展方法出现在类型的实例上,而不是类型本身(例如静态成员)。


2

尝试

"Hello".SafeFormat("{0} {1}", "two", "words")

太棒了。不知道为什么对于 string.SafeFormat() 没有这样做? - Chris Ballance
它没有字符串的引用。 - Daniel A. White
@Chris:因为字符串是类型的名称,而不是类型的实例。请注意,此示例实际上不起作用,因为SafeFormat方法需要两个字符串参数以及参数。 - Jon Skeet
我在思考这个方法需要被调用的正确方式(在实例上而不是类型上),并忽略了参数。 - Marek Karbarz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接