2016-05-02 40 views
-2

我試圖擴展'String'類。 到目前爲止,我必須在聲明的字符串對象上創建擴展函數。使用靜態函數擴展字符串類

String s = new String(); 
s = s.Encrypt(); 

但我想爲類本身創建一個擴展函數。 在這種情況下,像:String s = String.GetConfig("Test");

我試了一下,到目前爲止:

using System; 
using System.Runtime.CompilerServices; 

namespace Extensions.String 
{ 
    public static class StringExtensions 
    { 
     // Error 
     public string DecryptConfiguration 
     { 
      get 
      { 
       return "5"; 
      } 
     } 

     // Can't find this 
     public static string GetConfig(string configKey); 
     // Works, but not what I would like to accomplish 
     public static string Encrypt(this string thisString); 
    } 
} 

任何幫助將不勝感激。 提前謝謝!

+0

你不能做到這一點。 – SLaks

+0

有關擴展函數的詳細信息,請參閱:https://msdn.microsoft.com/en-us/library/bb383977.aspx –

回答

0

您無法添加您在類中像靜態方法一樣調用的擴展方法(例如var s = String.ExtensionFoo("bar"))。

擴展方法需要一個對象的實例(如在您的StringExtensions.Encrypt示例中)。基本上,擴展方法是靜態方法;他們的訣竅是使用關鍵字this啓用類似實例的調用(更多詳細信息here)。

你最好的賭注是某種包裝的:

using System; 
using System.Runtime.CompilerServices; 

namespace Extensions.String 
{ 
    public static class ConfigWrapper//or some other more appropriate name 
    { 
     public static string DecryptConfiguration 
     { 
      get 
      { 
       return "5"; 
      } 
     } 


     public static string GetConfig(string configKey); 

     public static string Encrypt(string str); 
    } 
} 

可稱爲是這樣的:

var str1 = ConfigWrapper.DecryptConfiguration; 
var str2 = ConfigWrapper.GetConfig("foo"); 
var str3 = ConfigWrapper.Encrypt("bar");