2013-06-04 21 views
4

這樣的方法我想創建我自己的方法,如我想在我自己的項目中使用的.ToString()創建像.ToString()

例如ToDecimalOrZero()我想將數據轉換爲十進制,或者如果數據爲空,則將其轉換爲零。

我知道我不應該在這裏要求代碼,但我沒有絲毫的想法,我怎麼能做到這一點。

任何人都可以幫我嗎?或者至少在某個地方介紹我......我有點失落。謝謝:)

+10

Google針對「擴展方法」。 –

+1

'我知道我不應該在這裏要求密碼準確:) – walther

+0

我認爲你的問題有點含糊。你的意思是你想要將這些方法添加到現有的類型中,還是你正在尋找一種通常創建方法的方法? –

回答

9

使用擴展方法:

namespace ExtensionMethods 
{ 
    public static class StringExtensions 
    { 
     public static decimal ToDecimalOrZero(this String str) 
     { 
      decimal dec = 0; 
      Decimal.TryParse(str, out dec); 
      return dec; 
     } 
    } 
} 

using ExtensionMethods; 
//... 
decimal dec = "154".ToDecimalOrZero(); //dec == 154 
decimal dec = "foobar".ToDecimalOrZero(); //dec == 0 
10

這裏如何編寫自己的擴展方法

namespace ExtensionMethods 
{ 
    public static class MyExtensions 
    { 
     public static int WordCount(this String str) 
     { 
      return str.Split(new char[] { ' ', '.', '?' }, 
          StringSplitOptions.RemoveEmptyEntries).Length; 
     } 
    } 
} 

MSDN

注意,擴展方法必須是靜態,還有一個例子包含擴展方法的類