2009-11-04 74 views
12

不知道我在做什麼錯在這裏。無法識別擴展方法。將擴展方法添加到字符串類 - C#

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

回答

31

你試圖調用它的類型字符串。您需要在字符串實例(例如,

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

的擴展方法的關鍵是,他們看起來像實例上擴展類型方法。您無法在擴展類型上創建看起來爲靜態方法的擴展方法。

2

嘗試

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

輝煌。不知道爲什麼它沒有這樣做string.SafeFormat()? – 2009-11-04 19:58:02

+0

它沒有對字符串的引用。 – 2009-11-04 19:58:49

+0

@Chris:因爲string是類型的名稱,而不是類型的實例。請注意,此示例實際上不起作用,因爲SafeFormat方法需要兩個字符串參數以及參數。 – 2009-11-04 19:59:16

10

您正在定義一個實例擴展方法,然後嘗試將其用作靜態方法。 (C#是不是能夠定義一個靜態擴展方法,雖然F#是爲此事)。

相反的:

result = string.SafeFormat("Hello"); 

你想要的東西,如:

result = "Hello".SafeFormat(); 

即你對字符串實例進行操作(在這種情況下爲「Hello」)。

3

擴展方法出現在類型的實例上,而不是類型本身(例如靜態成員)。