2016-05-02 12 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"); 
関連する問題