“所有方法”的 C# 委托或 Func?
我读过一些有关 Func 和委托的内容,它们可以帮助您将方法作为参数传递。 现在我有一个缓存服务,它有这样的声明:
public static void AddToCache<T>(T model, double millisecs, string cacheId) where T : class
public static T GetFromCache<T>(string cacheId) where T : class
所以在我想要缓存一些数据的地方,我检查它是否存在于缓存中(使用 GetFromCache),如果不存在,则从某处获取数据,然后添加它到缓存(使用 AddToCache)
现在我想用一个参数扩展 AddToCache 方法,该参数是调用以获取数据的类+方法 那么声明就是这样
public static void AddToCache<T>(T model, double millisecs, string cacheId, Func/Delegate methode) where T : class
然后这个方法可以检查缓存是否有数据,如果没有,则通过它提供的方法获取数据本身。
然后在调用代码中我可以说:
AddToCache<Person>(p, 10000, "Person", new PersonService().GetPersonById(1));
AddToCache<Advert>(a, 100000, "Advert", new AdvertService().GetAdverts(3));
我想要实现的是“如果缓存为空则获取数据并添加到缓存”逻辑仅放置在一个位置。
我希望这是有道理的:)
哦,顺便说一句,问题是:这可能吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能想要:
用法:
You probably want:
Usage:
像这样:
调用看起来像:
Like this:
The call would look like:
您可能想阅读此博客文章: 启动您的功能。它讨论了您正在使用相同方法解决的问题。
You might want to read this blog post: Get Your Func On . It discusses the problem you are solving with the same approach.