2009-11-04 6 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

을 시도합니다. 문자열 인스턴스으로 호출해야합니다. 예 : SafeFormat 방법은 실제로 완전히 어쨌든 첫 번째 매개 변수 (s)을 무시하기 때문에 당신이 그것을 원하는 일을하지 않습니다

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

인정 하듯이. 그것은 다음과 같아야합니다

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

점들이 예처럼 확장 된 유형에 방법을 볼 것입니다. 확장 유형에 static 메소드 인 것처럼 보이는 확장 메소드를 작성할 수 없습니다.

2

당신은 유형 문자열에 전화를하려는

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

브릴리언트. 왜 그것은 string.SafeFormat()에 대해 그렇게하지 않고 있었는지 궁금합니다. –

+0

문자열에 대한 참조가 없습니다. –

+0

@Chris : string은 형식의 이름이 아니기 때문에 형식의 인스턴스가 아닙니다. SafeFormat 메서드는 두 개의 문자열 인수와 매개 변수를 필요로하기 때문에이 예제는 실제로 작동하지 않습니다. –

10

인스턴스를 확장 메서드로 정의한 다음 메서드로 사용하려고합니다. (F 번호가 그 문제에 비록 C#을 정적 확장 메서드를 정의 할 수 없습니다.)

대신 : 당신은 즉

result = "Hello".SafeFormat(); 

:

result = string.SafeFormat("Hello"); 

당신이 뭔가를 원하는 문자열 인스턴스에서 작동합니다 (이 경우 "Hello").

3

확장 메서드는 형식 자체가 아닌 형식의 인스턴스 (예 : 정적 멤버)에 나타납니다.