1. A brief introduction to Fun
Fun and Action in C# are somewhat similar, both are a delegate method, the difference is that Func has a return value, while Action does not.
(T) The parameter types of the method this delegate encapsulates.
Remarks: Learn more about Fun to ( https://www.cnblogs.com/LipeiNet/p/4694225.html )
2. Simple example introduction
This side defines a dictionary globally, encapsulates a method, defines two parameters as string type, and a delegate. Assuming that the calling method passes in a key, if there is a dictionary, it returns a Value, and if it does not, it returns the key through the delegation!
Post a picture here to briefly introduce the code execution process
2. Use in conjunction with cache encapsulation
1). Get data
/// <summary> /// retrieve data /// </summary> public void GetConfigsValue() { var key = "SysKeyInfo"; var keyDic = GetDataLocalCache<string>(key, () => { using (EntityContext db = new EntityContext()) { var value = db.Configs.FirstOrDefault(o => o.Name == "SysKeyInfo").Value; return value; } }, DateTime.Now.AddHours(2)); }
2). Get the cache
/// <summary> /// Get cached data /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">缓存key</param> /// <param name="callBack">Delegate method name</param> /// <param name="timeout">Cache expiration time</param> /// <returns></returns> public static T GetDataLocalCache<T>(string key, Func<T> callBack, DateTime? timeout = null) { if (!timeout.HasValue) timeout = DateTime.Now.AddMinutes(5); var cache = HttpRuntime.Cache [key]; //If the cache does not exist or expires, execute the delegate method if (cache == null) { var result = callBack(); if (result != null) //Store the result of the delegate method execution in the cache HttpRuntime.Cache.Insert(key, result, null, timeout.GetValueOrDefault(), System.Web.Caching.Cache.NoSlidingExpiration); return result; } else { return (T)cache; } }
3. Summary
From the delegation of Func , we can see that it simplifies the tediousness of defining our own delegation, and at the same time it better combines the use of Lamdba . Reduced the role of custom functions. At the same time, there is also a disadvantage, that is, it is not easy to find where the error occurs. The use of Action delegate is the same as Func , so I won't talk about it here. I hope my summary can be helpful to you.
Advertise: Morrowind Movie https://www.chenfengdy.top/