2012-10-07 92 views
-1

我想添加一個方法來將字符串空格字符轉換爲下劃線(擴展方法),我部署了代碼,但爲什麼它不起作用?爲什麼我的擴展方法找不到?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string name = "moslem"; 
      string.SpaceToUnderScore(name); 
     } 

     public static string SpaceToUnderScore(this string source) 
     { 
      string result = null; 
      char[] cArray = source.ToArray(); 
      foreach (char c in cArray) 
      { 
       if (char.IsWhiteSpace(c)) 
       { 
        result += "_"; 
       } 
       else 
       { 
        result += c; 
       } 
      } 
      return result; 
     } 
    } 
} 

它爲什麼不起作用?

+0

並與它有空間輸入調用它。 – xxbbcc

+1

什麼不適用於它?你甚至沒有將字符串傳遞給有空格的函數。 –

+0

@ L.B你應該做出這個答案 –

回答

3

首先把你的擴展方法的靜態類然後調用爲name.SpaceToUnderScore()

var newstr = "a string".SpaceToUnderScore(); 


public static class SomeExtensions 
{ 
    public static string SpaceToUnderScore(this string source) 
    { 
     return new string(source.Select(c => char.IsWhiteSpace(c) ? '_' : c).ToArray()); 
     //or 
     //return String.Join("",source.Select(c => char.IsWhiteSpace(c) ? '_' : c)); 
    } 
} 
0

擴展方法應該寫成靜態類。

public static class StringExtension 
{ 
    public static string SpaceToUnderScore(this string source) 
    { 
     string result = null; 
     char[] cArray = source.ToArray(); 
     foreach (char c in cArray) 
     { 
      if (char.IsWhiteSpace(c)) 
      { 
       result += "_"; 
      } 
      else 
      { 
       result += c; 
      } 
     } 
     return result; 
    } 
} 
0

沒有在您的擴展方法改變代碼,擴展方法添加到一個靜態類:

public static class MyExtensions // Name this class to whatever you want, but make sure it's static. 
{ 
    public static string SpaceToUnderScore(this string source) 
    { 
     string result = null; 
     char[] cArray = source.ToArray(); 
     foreach (char c in cArray) 
     { 
      if (char.IsWhiteSpace(c)) 
      { 
       result += "_"; 
      } 
      else 
      { 
       result += c; 
      } 
     } 
     return result; 
    } 
} 

然後調用它像這樣:

string name = "moslem"; 
string underscoreName = name.SpaceToUnderScore(); // Omit the name parameter (prefixed with this) when called like this on the string instance. 

// This would work to: 
string underscoreName = MyExtentions.SpaceToUnderScore(name); 

如果您沒有找到擴展方法,請確保您使用的是靜態類的名稱空間。

0
public static class MyStringExtenstionClass 
{ 

    public static string SpaceToUnderScore(this string source) 
    { 
     string result = null; 
     char[] cArray = source.ToArray(); 
     foreach (char c in cArray) 
     { 
      if (char.IsWhiteSpace(c)) 
      { 
       result += "_"; 
      } 
      else 
      { 
       result += c; 
      } 
     } 
     return result; 
    } 
} 

像這樣

string name = "John Doe"; 
name = name.SpaceToUnderScore(); //no argument and called on instance of string 
相關問題