在调用一个自定义的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; }
}
}