C#、ASP.NET通用扩展工具类之LogicSugar

说明一下性能方面 还可以接受 循环1000次普通Switch是用了0.001秒 ,扩展函数为0.002秒  , 如果是大项目在有负载均衡的情况下完全可以无视掉,小项目也不会计较这点性能了。

注意需要引用 “SyntacticSugar”

用法:

//【Switch】
string bookKey = "c#";

//以前写法
string myBook = "";
switch (bookKey)
{
  case "c#":
    myBook = "asp.net技术";
    break;
  case "java":
    myBook = "java技术";
    break;
  case "sql":
    myBook = "mssql技术";
    break;
  default:
    myBook = "要饭技术";
    break;//打这么多break和封号,手痛吗?
}

//现在写法
myBook =bookKey.Switch().Case("c#", "asp.net技术").Case("java", "java技术").Case("sql", "sql技术").Default("要饭技术").Break();//点的爽啊

/**
   C#类里看不出效果, 在mvc razor里  ? 、&& 或者 || 直接使用都会报错,需要外面加一个括号,嵌套多了很不美观,使用自定义扩展函数就没有这种问题了。

 */

bool isSuccess = true;

//【IIF】
//以前写法
var trueVal1 = isSuccess ? 100 :0;
//现在写法
var trueVal2 = isSuccess.IIF(100);

//以前写法
var str = isSuccess ? "我是true" : "";
//现在写法
var str2 = isSuccess.IIF("我是true");

//以前写法
var trueVal3 = isSuccess ? 1 : 2;
//现在写法
var trueVal4 = isSuccess.IIF(1, 2);

string id = "";
string id2 = "";

//以前写法
isSuccess = (id == id2) && (id != null && Convert.ToInt32(id) > 0);
//现在写法
isSuccess = (id == id2).And(id != null, Convert.ToInt32(id) > 0);

//以前写法
isSuccess = id != null || id != id2;
//现在写法
isSuccess = (id != null).Or(id != id2);

源码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SyntacticSugar
{
  /// <summary>
  /// ** 描述:逻辑糖来简化你的代码
  /// ** 创始时间:2015-6-1
  /// ** 修改时间:-
  /// ** 作者:sunkaixuan
  /// </summary>
  public static class LogicSugarExtenions
  {
    /// <summary>
    /// 根据表达式的值,来返回两部分中的其中一个。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="thisValue"></param>
    /// <param name="trueValue">值为true返回 trueValue</param>
    /// <param name="falseValue">值为false返回 falseValue</param>
    /// <returns></returns>
    public static T IIF<T>(this bool thisValue, T trueValue, T falseValue)
    {
      if (thisValue)
      {
        return trueValue;
      }
      else
      {
        return falseValue;
      }
    }

    /// <summary>
    /// 根据表达式的值,true返回trueValue,false返回string.Empty;
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="thisValue"></param>
    /// <param name="trueValue">值为true返回 trueValue</param>
    /// <returns></returns>
    public static string IIF(this bool thisValue, string trueValue)
    {
      if (thisValue)
      {
        return trueValue;
      }
      else
      {
        return string.Empty;
      }
    }

    /// <summary>
    /// 根据表达式的值,true返回trueValue,false返回0
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="thisValue"></param>
    /// <param name="trueValue">值为true返回 trueValue</param>
    /// <returns></returns>
    public static int IIF(this bool thisValue, int trueValue)
    {
      if (thisValue)
      {
        return trueValue;
      }
      else
      {
        return 0;
      }
    }

    /// <summary>
    /// 根据表达式的值,来返回两部分中的其中一个。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="thisValue"></param>
    /// <param name="trueValue">值为true返回 trueValue</param>
    /// <param name="falseValue">值为false返回 falseValue</param>
    /// <returns></returns>
    public static T IIF<T>(this bool? thisValue, T trueValue, T falseValue)
    {
      if (thisValue == true)
      {
        return trueValue;
      }
      else
      {
        return falseValue;
      }
    }

    /// <summary>
    /// 所有值为true,则返回true否则返回false
    /// </summary>
    /// <param name="thisValue"></param>
    /// <param name="andValues"></param>
    /// <returns></returns>
    public static bool And(this bool thisValue, params bool[] andValues)
    {
      return thisValue && !andValues.Where(c => c == false).Any();
    }

    /// <summary>
    /// 只要有一个值为true,则返回true否则返回false
    /// </summary>
    /// <param name="thisValue"></param>
    /// <param name="andValues"></param>
    /// <returns></returns>
    public static bool Or(this bool thisValue, params bool[] andValues)
    {
      return thisValue || andValues.Where(c => c == true).Any();
    }

    /// <summary>
    /// Switch().Case().Default().Break()
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="thisValue"></param>
    /// <returns></returns>
    public static SwitchSugarModel<T> Switch<T>(this T thisValue)
    {
      var reval = new SwitchSugarModel<T>();
      reval.SourceValue = thisValue;
      return reval;

    }

    public static SwitchSugarModel<T> Case<T, TReturn>(this SwitchSugarModel<T> switchSugar, T caseValue, TReturn returnValue)
    {
      if (switchSugar.SourceValue.Equals(caseValue))
      {
        switchSugar.IsEquals = true;
        switchSugar.ReturnVal = returnValue;
      }
      return switchSugar;
    }

    public static SwitchSugarModel<T> Default<T, TReturn>(this SwitchSugarModel<T> switchSugar, TReturn returnValue)
    {
      if (switchSugar.IsEquals == false)
        switchSugar.ReturnVal = returnValue;
      return switchSugar;
    }

    public static dynamic Break<T>(this SwitchSugarModel<T> switchSugar)
    {
      string reval = switchSugar.ReturnVal;
      switchSugar = null;//清空对象,节约性能
      return reval;
    }

    public class SwitchSugarModel<T>
    {
      public T SourceValue { get; set; }
      public bool IsEquals { get; set; }
      public dynamic ReturnVal { get; set; }
    }

  }

}
(0)

相关推荐

  • Asp.Net MVC中配置Serilog的方法

    一.Serilog介绍 Serilog 是一种非常简便记录log 的处理方式,使用Serilog可以生成本地的text文件, 也可以通过 Seq 来在Web界面中查看具体的log内容. 二.配置方法 接下来就简单的介绍一下在Asp.Net MVC中如何配置是Serilog 生效: 1):下载并且安装Seq,具体的下载URL 为 [http://getseq.net/Download],安装到默认的路径之后,实际上时候启动了一个Win Service,并且监听的端口号默认为 5341. 安装的最后

  • Asp.net Mvc 身份验证、异常处理、权限验证(拦截器)实现代码

    1.用户登录 验证用户是否登录成功步骤直接忽略,用户登录成功后怎么保存当前用户登录信息(session,cookie),本文介绍的是身份验证(其实就是基于cookie)的,下面看看代码. 引入命名空间 using System.Web.Security; 复制代码 代码如下: Users ModelUser = new Users() { ID = 10000, Name = UserName, UserName = UserName, PassWord = PassWord, Roles =

  • ASP.NET MVC中为DropDownListFor设置选中项的方法

    在MVC中,当涉及到强类型编辑页,如果有select元素,需要根据当前Model的某个属性值,让Select的某项选中.本篇只整理思路,不涉及完整代码. □ 思路 往前台视图传的类型是List<SelectListItem>,把SelectListItem选中项的Selected属性设置为true,再把该类型对象实例放到ViewBag,ViewData或Model中传递给前台视图. 通过遍历List<SelectListItem>类型对象实例 □ 控制器 public Action

  • asp.net log4net的使用方法

    刚开始接触asp.net,关于日志记录怎么能少,因此简单记录一下log4net的配置和使用,以防以后忘记.   首先引入log4net.dll,关于这个文件自己百度下载下. 然后配置一下有关配置,在web.config中加入在configuration节点下 <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log

  • asp.net MVC实现无组件上传图片实例介绍

    例子: 如我想上传一个图片到服务器端:asp页面 复制代码 代码如下: <form id="form1" runat="server" action="/bookIndex/fileUpLoad/(你准备处理的 ActionResult)" method="post" enctype="multipart/form-data"> <input type="file" i

  • asp.net mvc下拉框Html.DropDownList 和DropDownListFor的常用方法

    一.非强类型: Controller: ViewData["AreId"] = from a in rp.GetArea()                                select new SelectListItem {                                Text=a.AreaName,                                Value=a.AreaId.ToString()                   

  • IIS7 配置大全(ASP.NET 2.0, WCF, ASP.NET MVC,php)

    一.IIS7.0 配置 ASP.NET2.0 1.ASP.NET 2.0 部署 1)首先打开win7 的特性,路径我已标注 下面选中的是ASP.NET2.0, 如果要支持ASP.NET1.1,你的选中IIS6兼容 2.)设置安全选项 3)添加.Net经典应用程序池 4)将站点转换为Application 5)为站点添加 yourmachinename\IIS_IUSRS权限 6.)右键站点-Manage Application-Advanced Setting 设置当前站点为Classic .N

  • 使用asp.net MVC4中的Bundle遇到的问题及解决办法分享

    背景    之前有过使用MVC3的经验,也建过MVC4的基本样例看过,知道有bundle这么一个方法. 近日想建个网站使用MVC4,但是我觉得在基本样例上改不好,有太多无用的东西,所以就建了一个空白的MVC的程序,然后自己写需要的东西, 将程序的目标框架从4.5降到了4.0(我使用的是VS2013),问题就来了. 问题及解决办法 1.降了目标框架之后,vs报一个警告:NuGet程序包是使用不同于当前目标框架的目标框架安装的,需要更新System.Web.Http,之前有用过NuGet, 但是只是

  • ASP.NET MVC 5使用X.PagedList.Mvc进行分页教程(PagedList.Mvc)

    ASP.NET MVC中进行分页的方式有多种,但在NuGet上使用最广泛的就是用PagedList.X.PagedList.Mvc进行分页.(原名为:PagedList.Mvc,但是2014年开始,作者将项目名称改名字为"X.PagedList.Mvc"),用这个插件的话会非常便利,大家可以试试,接下来将给大家讲下如何安装这个NuGet插件. ASP.NET MVC 5使用X.PagedList.Mvc进行分页教程(原名为PagedList.Mvc) 1.工具--NuGet 程序包管理

  • ASP.NET MVC DropDownList数据绑定及使用详解

    一:DropDownList 1.1 DropDownList绑定数据 1.1.1 DropDownList 固定绑定 这种方式适合那些已经固定的数据绑定到DropDownList上. 例 复制代码 代码如下: <asp:DropDownList runat="server" ID="ddlArea" Width="120px" > <asp:Listitem value="0">选择性别</as

随机推荐