使用反射代替不断添加的if-else来实现代码的可扩展性
在調用一個自定義的GeneralHandler類里面的一個方法,該方法是針對數據庫的一張表的所有操作(CRUD),根據傳入的DealType來判斷做那種操作
代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace WinFormPro
{
/// <summary>
/// 接收外部訪問的處理類
/// </summary>
public class GeneralHandler
{
/// <summary>
/// 處理報價單的方法(增刪改查)
/// </summary>
/// <param name="quote"></param>
/// <param name="dealType"></param>
/// <returns></returns>
public QuoteHandlerReturnModel DealQuote(Quote quote, string dealType)
{
QuoteHandlerReturnModel returnModel = new QuoteHandlerReturnModel();
QuoteService quoteHandler = new QuoteService();
Type type = quoteHandler.GetType();
MethodInfo[] quoteMethodList = type.GetMethods(BindingFlags.Instance | BindingFlags.Public);
foreach (var method in quoteMethodList)
{
if (dealType.Equals(method.Name,StringComparison.OrdinalIgnoreCase))
{
returnModel=(QuoteHandlerReturnModel)method.Invoke(quoteHandler, new object[] { quote });//這里代替了那些if-else的判斷(但是前提是:這些被調用的方法必須有相同的參數)
}
}
return returnModel;
}
}
/// <summary>
/// 操作數據庫報價單的Service
/// </summary>
public class QuoteService
{
public QuoteHandlerReturnModel Create(Quote quote)
{
//todo:向數據庫增加報價單
return new QuoteHandlerReturnModel();
}
public QuoteHandlerReturnModel Delete(Quote quote)
{
//todo:在數據庫中刪除一條報價單
return new QuoteHandlerReturnModel();
}
public QuoteHandlerReturnModel Update(Quote quote)
{
//todo:在數據庫中更新這條報價單
return new QuoteHandlerReturnModel();
}
public QuoteHandlerReturnModel Get(Quote quote)
{
//todo:在數據庫中更新這條報價單
return new QuoteHandlerReturnModel();
}
}
/// <summary>
/// 報價單Model
/// </summary>
public class Quote
{
public int Id { get; set; }
public string QuoteNo { get; set; }
public string OwnerName { get; set; }
public DateTime QuoteDate { get; set; }
}
/// <summary>
/// 所有的報價單操作的方法的返回值類型
/// </summary>
public class QuoteHandlerReturnModel
{
public bool IsSuccess { get; set; }
public Quote quote { get; set; }
}
}
轉載于:https://www.cnblogs.com/xiaosongluffy/p/3715389.html
總結
以上是生活随笔為你收集整理的使用反射代替不断添加的if-else来实现代码的可扩展性的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET使用log4Net日志组件
- 下一篇: 类库dll引用不成功问题