How pass Func to method parameter

后端 未结 1 1902
有刺的猬
有刺的猬 2021-01-16 20:00

I have found code for Get/Set cache item, but I don\'t know how I can call this method, eg. how pass proper Func getData to this method?



        
相关标签:
1条回答
  • 2021-01-16 20:42

    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 )
        {
           ...
        }
    }
    

    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>(); }
    

    and

    var myCache = new Cache<IEnumerable<MyObject>>();
    var repo = new MyRepository();
    IEnumerable<MyObject> data = null;
    myCache.TryGetOrSet("some_key", repo.MyDataAccessMethod, out data);
    

    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:

    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) ;
    
    0 讨论(0)
提交回复
热议问题