• 使用反射代替不断添加的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; }
    }
    }

  • 相关阅读:
    Blend3中创建的Silverlight程序在设计模式下无法显示图片的解决办法
    创建Silverlight Bussiness Application时报错的解决
    .NET 2.0 字符串比较
    ASP.NET 客户端缓存
    AjaxPro部署成功
    遭遇反序列化异常:"在分析完成之前就遇到流结尾"
    正则表达式
    哈哈,终于申请获得批准了!
    ClientScript.RegisterClientScriptInclude注册脚本
    今天经过一场深有体会的谈话终于决定了我2012的方向
  • 原文地址:https://www.cnblogs.com/xiaosongluffy/p/3715389.html
Copyright © 2020-2023  润新知