2009-11-04 18 views
12

Nie jestem pewien, co robię źle tutaj. Metoda rozszerzenia nie jest rozpoznawana.Dodawanie metody rozszerzenia do klasy ciągów - 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; 
     } 
    } 
} 

Odpowiedz

31

Próbujesz wywołać go na ciąg typu. Musisz wywołać to na instancji ciąg, np.

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

Trzeba przyznać, że nie zrobi tego, co chcesz go, ponieważ metoda SafeFormat jest rzeczywiście całkowicie ignorując pierwszy parametr (s) W każdym razie. Powinno to wyglądać tak:

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

Następnie można wywołać:

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

Punktem metod rozszerzenie jest to, że wyglądają jak przykład metod na rozszerzonym typu. Nie można tworzyć metod rozszerzania, które wydają się być metodami rozszerzonego typu.

2

spróbować

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

Genialny. Zastanawiam się, dlaczego nie robiono tego dla string.SafeFormat()? –

+0

Nie ma odniesienia do łańcucha. –

+0

@Chris: Bo łańcuch jest nazwą typu, a nie instancją typu. Zauważ, że ten przykład nie zadziała, ponieważ metoda SafeFormat wymaga dwóch argumentów, jak również parametrów. –

10

Ty definiując instancja metodę rozszerzenia, a następnie próbuje użyć go jako statycznej metody. (C# nie jest zdolny do definiowania statyczną metodę rozszerzenia, choć F # jest o tym mowa).

Zamiast:

result = string.SafeFormat("Hello"); 

chcesz coś takiego:

result = "Hello".SafeFormat(); 

czyli jesteś działa na instancji napisu ("Hello" w tym przypadku).

3

Metody rozszerzeń pojawiają się w wystąpieniach typu, a nie w samym typie (np. W statycznych elementach).