2017-11-28 10 views
0

私は多くの方法を持っており、キャッシュにその一部を入れる必要があります。しかし、私はそれがそれぞれの方法を編集したくない。戻り値をパラメータとして動的メソッドを渡すにはどうすればよいですか?

どのようにパラメータとして戻り値を持つ動的メソッドを渡すことができますか?親切に私のコードで私の質問のいくつかのコメントを確認してください。

ありがとうございます。

private string GetUserName(string userId) 
     { 
      // how can I pass the method as parameter? 
      // Method is dynamic and can be any method with parameter(s) and return value 
      return CacheIt<string>(item => GetUserNameFromDb(userId)); 
     } 

     private T CacheIt<T>(Action<T> action) // Im not sure if this an Action 
     { 
      var key = "UserInfo." + userId; // how can I get the value of the parameter? 

      var cache = MemoryCache.Default; 
      var value = (T) cache[key]; 

      if (value != null) 
       return value; 

      value = action(); // how can I call the action or the method 

      var policy = new CacheItemPolicy { SlidingExpiration = new TimeSpan(1, 0, 0) }; 
      cache.Add(key, value, policy); 

      return value; 

     } 

     private string GetUserNameFromDb(string userId) 
     { 
      return "FirstName LastName"; 
     } 
+0

メソッドをパラメータとして渡す必要がある場合は、[delegate](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/using-delegates)を使用する必要があります。 'Action'、' Func'、 'Predicate' [https://stackoverflow.com/questions/566860/delegates-predicate-action-func]のような定義済みの一般的なものがあります。 – royalTS

答えて

1

CacheItのように変更します。入力パラメータはオブジェクト型としてメソッドに渡され、キャッシュキーを作成するために、入力オブジェクトがJsonとしてシリアル化され、json結果がMD5に計算されます。 MD5結果はキーとしてキャッシュに保存されます。また、アクションは値を返しません。アクションの代わりにFuncを使用しました。私たちはキャッシングの価値を返すことを期待しています。

private T2 CacheIt<T2>(Func<T2> func, object input) 
    { 
     var key = CreateMD5(JsonConvert.SerializeObject(input)); 
     var cache = MemoryCache.Default; 
     var value = cache.Get(key); 
     if (value != null) 
     { 
      return (T2)value; 
     } 
     value = func(); 
     var policy = new CacheItemPolicy { SlidingExpiration = new TimeSpan(1, 0, 0) }; 
     cache.Add(key, value, policy); 
     return (T2)value; 
    } 

    private string CreateMD5(string input) 
    { 
     using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create()) 
     { 
      byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); 
      byte[] hashBytes = md5.ComputeHash(inputBytes); 
      StringBuilder sb = new StringBuilder(); 
      for (int i = 0; i < hashBytes.Length; i++) 
      { 
       sb.Append(hashBytes[i].ToString("X2")); 
      } 
      return sb.ToString(); 
     } 
    } 

最後に、GetUserNameとGetUserNameFromDb方法は次のようになります。

private string GetUserName(string userId,string anotherParameter) 
    { 
     return CacheIt<string>(() => GetUserNameFromDb(userId, anotherParameter), new { userId,anotherParameter }); 
    } 

    private string GetUserNameFromDb(string userId, string anotherParameter) 
    { 
     return "FirstName LastName"; 
    } 

です。

GetUserName("1","AnotherParameter"); 

注:たぶんCacheIt方法でfuncから直接 からの入力パラメータを取得するためのより良い方法があるかもしれません。

0

、我々はそれが「アウト」と「REF」の変数で正常に動作します

public T CacheIt<T>(object container,string methodName,params object[] parameterlist) 
    { 
     MethodInfo func = container.GetType().GetMethod(methodName); 
     var cache = MemoryCache.Default; 
     T value = (T)cache.Get(func.Name); 
     if(value!=null) 
     { 
      return value; 
     } 
     value = (T)func.Invoke(container,parameterlist); 

     cache.Add(func.Name, value,new CacheItemPolicy()); 
     return value; 

    } 

    public void PrintUserName() 
    { 
    CacheIt<string>(this,nameof(this.GetUserName),"1"); 
     CacheIt<string>(this, nameof(this.GetFullName), "Raghu","Ram"); 
     Console.Read(); 
    } 

    public string GetUserName(string userId) 
    { 
     // how can I pass the method as parameter? 
     // Method is dynamic and can be any method with parameter(s) and return value 
     //return CacheIt<string>(item => GetUserNameFromDb(userId)); 
     return $"UserId : {userId} & UserName:Vaishali"; 
    } 

    public string GetFullName(string FirstName,string LastName) 
    { 
     return $"FullName : {string.Concat(FirstName," ",LastName)}"; 
    } 

によって動的にかかわらず、メソッド定義の方法を渡すことができますが、アウトとref変数の値を取得することは容易ではありませんこれのために、私たちはParameterInfoにもっと多くの作業をしなければなりません。

関連する問題