2009-11-04 20 views
12

Burada yanlış yaptığımdan emin değilim. Uzantı yöntemi tanınmadı.String sınıfına bir uzantı yöntemi ekleme - 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; 
     } 
    } 
} 

cevap

31

deneyin. Bir dize örnek, ör. SafeFormat yöntemi aslında tamamen zaten ilk parametre (s) görmezden olduğu için, bunu istediğini yapmayacağım

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

Kuşkusuz. Bu gibi görünmelidir:

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

Sonra arayabilirsiniz: uzatma yöntemleri

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

nokta onlar örneği gibi genişletilmiş tipine yöntemleri bakmak olmasıdır. Uzatılmış türde statik yöntemleri gibi görünen uzantı yöntemleri oluşturamazsınız.

2

Sen tip ipe diyoruz çalışıyoruz

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

Parlak. Merak etmek için neden bunu yapmadığını merak ediyorum.SafeFormat()? –

+0

Bir dizeye referans yok. –

+0

@Chris: Çünkü dize, türün değil, türün adıdır. Bu örneğin aslında çalışmayacağını unutmayın, çünkü SafeFormat yöntemi, parametrelerin yanı sıra iki dize argümanı gerektirir. –

10

Bir örneği uzatma yöntemini tanımlayan ve daha sonra bir statik yöntemi olarak kullanmaya çalışıyorlar. (F # bu konuda olsa C#, statik bir uzantısı yöntemi tanımlayan yeteneğine değildir.)

yerine: Sen yani

result = "Hello".SafeFormat(); 

:

result = string.SafeFormat("Hello"); 

gibi bir şey istemek dize örneğinde çalışma (bu durumda "Merhaba").

3

Uzantı yöntemleri, türünün değil (örneğin, statik üyeler) bir türdeki örneklerde görünür.

İlgili konular