C # delegate or func for all methods?

I read something about Func and delegates and that they can help you 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 the 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 add it to the cache (using AddToCache)

Now I want to extend the AddToCache method with a parameter, which is a class + method to call data. Then the declaration will be like this:

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

Then this method can check whether the cache has data or not, and if not, get the data itself using the method that it 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));

, , "if cache is empty get data and add to cache" .

, :)

, , : ?

+3
3

:

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

:

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

, :

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

:

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

You might want to read this blog post: Get Your Func On . It discusses a problem that you solve using the same approach.

+1
source

Source: https://habr.com/ru/post/1742415/


All Articles