1.委托
2.linq
3.linq to sql
4.AOP封装-委托嵌套
委托封装:能把一个方法包装成一个变量,然后传递,所以用委托来完成逻辑拆分
把固定的固定,只关注通用逻辑,完成固定,把可变的提出交给调用者指定,更稳定,这就是代码封装
应用场景:
switch case
1.student.SayHi("李恒", Student.PeopleType.Chinese)
Action<string> action = new Action<string>(s => Console.WriteLine($"早上好,{s}"));
student.SayHiAdvanced("李恒", s => Console.WriteLine($"早上好,{s}"));
public void SayHiAdvanced(string name,Action<string> sayHiByCountry)
{
console.WriteLine("prepare say hi");
sayHiByCountry.Invoke(name);
console.WriteLine("after say hi");
}
通用缓存读取
2.错误处理:
//new Action(() =>
//student.SayHi("李恒", Student.PeopleType.Chinese)
//).SafeInvoke();
/// <summary>
/// 提供安全调用,抓取任何异常,打印日志
/// </summary>
/// <param name="act"></param>
public static void SafeInvoke(this Action act)
{
try
{
act.Invoke();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
3. 缓存处理
public static object ShowCache()
{
string key = "ShowCache-1123";
if (DelegateExtend.Exist(key))
{
return DelegateExtend.Get(key);
}
else
{
Thread.Sleep(1000);
object oValue = "ssdqdhadshaksfhkasf";
DelegateExtend.Add(key, oValue);
return oValue;
}
}
4. 数据库调用处理
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <param name="func"></param>
/// <returns></returns>
public static T Excute<T>(string sql, Func<SqlCommand, T> func)
{
using (SqlConnection conn = new SqlConnection(""))
{
//conn.Open();
SqlTransaction trans = conn.BeginTransaction();
try
{
SqlCommand command = new SqlCommand(sql, conn);
T t = func(command);
trans.Commit();
return t;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
trans.Rollback();
throw ex;
}
}
}
5.LINQ TO OBJECT:封装一系列的操作,内存数据;linq to sql:llinq操作数据库;linq to redis,linq to excel; linq to everthing
public static class CustomLinqExtend
{
public static List<T> ElevenWhere<T>(this List<T> lists, Func<T, bool> func)
{
List<T> tList = new List<T>();
foreach (var student in lists)
{
if (func.Invoke(student))
{
tList.Add(student);
}
}
return tList;
}
}