【问题标题】:Adding an extension method to the string class - C#向字符串类添加扩展方法 - C#
【发布时间】:2010-12-13 04:03:02
【问题描述】:

不知道我在这里做错了什么。无法识别扩展方法。

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

【问题讨论】:

    标签: c# .net string extension-methods string-formatting


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      您正在定义一个 instance 扩展方法,然后尝试将其用作 static 方法。 (C# 不能定义静态扩展方法,尽管 F# 是为了这件事。)

      代替:

      result = string.SafeFormat("Hello");
      

      你想要这样的东西:

      result = "Hello".SafeFormat();
      

      即您正在对字符串实例进行操作(在本例中为“Hello”)。

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          试试

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

          【讨论】:

          • 太棒了。想知道为什么它不为 string.SafeFormat() 这样做吗?
          • 它没有对字符串的引用。
          • @Chris:因为 string 是类型的名称,而不是类型的实例。请注意,此示例实际上不起作用,因为 SafeFormat 方法需要两个字符串参数以及参数。
          • 我在考虑需要调用此方法的正确方式(在实例上而不是类型上)并忽略了参数
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-26
          • 2014-03-06
          • 2017-04-17
          相关资源
          最近更新 更多