更新时间:2022-05-05 15:40:10
您的示例缺少 T
的声明-但您已在类中对其进行了注释
Your example is missing the declaration of T
- but you've commented its on the class
public class Cache<T>
{
public void TryGetOrSet( string cacheKey, Func<T> getData, out T returnData, CacheItemPolicy policy = null )
{
...
}
}
在这种情况下,您可以将与预期签名匹配的任何方法(匿名或其他)传递给 getData
.所以说你有一个实例
In this case, you can pass to getData
any method (anonymous or otherwise) which matches the signature expected. So say you have an instance
var myCache = new Cache<string>();
然后,任何不带参数且返回字符串的方法都可以作为该参数传递.
Then any method which takes no parameters and returns a string can be passed as that parameter.
string value = null;
myCache.TryGetOrSet("some_key", () => "foo", out value);
此外,如果您有一种方法可以将数据传输到某个地方,则可以传递对其的引用
Also if you have a method which gets your data somewhere a reference to that can be passed
// somewhere eg "MyRepository"
public IEnumerable<MyObject> MyDataAccessMethod() { return Enumerable.Empty<MyObject>(); }
和
var myCache = new Cache<IEnumerable<MyObject>>();
var repo = new MyRepository();
IEnumerable<MyObject> data = null;
myCache.TryGetOrSet("some_key", repo.MyDataAccessMethod, out data);
作为旁注,您已经声明了返回 void
的方法,但是您返回了布尔值-这对于 TryXXX
方法应该是有意义的返回一个布尔值以表示成功.
As a side note, you've declared the method to return void
but youre returning a boolean - this makes sense as a TryXXX
method should return a boolean to indicate success.
public bool TryGetOrSet( string cacheKey, Func<T> getData, out T returnData, CacheItemPolicy policy = null )
{
...
}
响应您的更新:
In response to your update:
第一个问题:通过使用TryGetOrSet方法,如何添加要缓存的项(键:userName变量,值:lastName变量)?当然,当缓存中不存在该项目时
First question: By using method TryGetOrSet how I can add item (key : userName variable, value: lastName variable) to cache? Of course when this item doesn't exists in cache
var cache = new Cache<string>("UserInfo");
var userName = "test";
var lastName = "test2";
string result = null;
TryGetOrSet(userName, () => lastName, out result) ;