简体   繁体   中英

C# delegate or Func for 'all methods'?

i've read something about Func's and delegates and that they can help you to pass a method as a parameter. Now i have a cachingservice, and it has this declaration:

public static void AddToCache<T>(T model, double millisecs, string cacheId) where T : class
public static T GetFromCache<T>(string cacheId) where T : class

So in a place where i want to cache some data, i check if it exists in the cache (with GetFromCache) and if not, get the data from somewhere, and the add it to the cache (with AddToCache)

Now i want to extend the AddToCache method with a parameter, which is the class+method to call to get the data Then the declaration would be like this

public static void AddToCache<T>(T model, double millisecs, string cacheId, Func/Delegate methode) where T : class

Then this method could check wether the cache has data or not, and if not, get the data itself via the method it got provided.

Then in the calling code i could say:

AddToCache<Person>(p, 10000, "Person", new PersonService().GetPersonById(1));
AddToCache<Advert>(a, 100000, "Advert", new AdvertService().GetAdverts(3));

What i want to achieve is that the 'if cache is empty get data and add to cache' logic is placed on only one place.

I hope this makes sense :)

Oh, by the way, the question is: is this possible?

You probably want:

public static void AddToCache<T>(T model, double millisecs, string cacheId, 
   Func<T> methode) where T : class;

Usage:

AddToCache<Person>(p, 10000, "Person", 
       () => new PersonService().GetPersonById(1));

Like this:

public static void AddToCache<T>(T model, double millisecs, string cacheId, Func<T> getValueFunction ) where T : class
{
  // if miss:
  var person = getValueFunction.Invoke();
}

The call would look like:

AddToCache( p , 1, "Person", () => new PersonService().GetPersonById(1) );

You might want to read this blog post: Get Your Func On . It discusses the problem you are solving with the same approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM