Expression基礎體驗

来源:http://www.cnblogs.com/kingge/archive/2016/06/22/5608748.html
-Advertisement-
Play Games

...


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Unit
{
    class T
    {
        public void Test()
        {
            Console.WriteLine("Test Class!");
        }
    }
    class S
    {
        private List<int> ids = new List<int>();
        public string Name { set; get; }

        public List<int> Ids { set { ids = value; } get { return ids; } }
    }
    class ET
    {
        public void Run()
        {
            //add
            Add(4, 5);//+
            AddAssign(4, 5);
            Subtract(5, 4);//-
            SubtractAssign(5,4);
            Multiply(4,5);
            MultiplyAssign(4,5);
            Divide(4, 2);
            DivideAssign(4,2);
            Decrement(3);//i--;
            Increment(3);//++
            Modulo();
            
            And(true, false); //&
            AndAlso(true, false);  //&&
            Or(true, false);
            OrElse(true, false);  //||
            LessThan(4, 5);
            Coalesce(1, 2);
            Coalesce(null, 2);
            Is();
            If();
            IfElse();
            Condition();
            Switch(5);
            Loop(9);
            TypeAs();
            Convert();
            New();
            NewArray();
            NewArrayBounds();
            ListInit();
            ListBind();
        }
        /// <summary>
        /// +
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        private void Add(int a,int b)
        {
            var left = Expression.Parameter(typeof(int));
            var right = Expression.Parameter(typeof(int));
            Expression exp = Expression.Add(left, right);
            Expression<Func<int, int, int>> lambda = Expression.Lambda<Func<int, int, int>>(exp, new ParameterExpression[] { left, right });
            var l = lambda.Compile();
            var r = l(a, b);
            Console.WriteLine(r);
        }

        public static int Add2(int a,int b)
        {
            return 100;
        }

        /// <summary>
        /// 利用方法+
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        private void AddAssign(int a, int b)
        {
            var left = Expression.Parameter(typeof(int));
            var right = Expression.Parameter(typeof(int));
            Expression exp = Expression.AddAssign(left, right, this.GetType().GetMethod("Add2"));
            Expression<Func<int, int, int>> lambda = Expression.Lambda<Func<int, int, int>>(exp, new ParameterExpression[] { left, right });
            var l = lambda.Compile();
            var r = l(a, b);
            Console.WriteLine(r);
        }
        /// <summary>
        /// &
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        private void And(bool a, bool b)
        {
            var left = Expression.Parameter(typeof(bool));
            var right = Expression.Parameter(typeof(bool));
            Expression exp = Expression.And(left, right);
            Expression<Func<bool, bool, bool>> lambda = Expression.Lambda<Func<bool, bool, bool>>(exp, new ParameterExpression[] { left, right });
            var l = lambda.Compile();
            var r = l(a, b);
            Console.WriteLine(r);
        }
        /// <summary>
        /// &&
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        private void AndAlso(bool a, bool b)
        {
            var left = Expression.Parameter(typeof(bool));
            var right = Expression.Parameter(typeof(bool));
            Expression exp = Expression.AndAlso(left, right);
            Expression<Func<bool, bool, bool>> lambda = Expression.Lambda<Func<bool, bool, bool>>(exp, new ParameterExpression[] { left, right });
            var l = lambda.Compile();
            var r = l(a, b);
            Console.WriteLine(r);
        }
        /// <summary>
        /// |
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        private void Or(bool a, bool b)
        {
            var left = Expression.Parameter(typeof(bool));
            var right = Expression.Parameter(typeof(bool));
            Expression exp = Expression.Or(left, right);
            Expression<Func<bool, bool, bool>> lambda = Expression.Lambda<Func<bool, bool, bool>>(exp, new ParameterExpression[] { left, right });
            var l = lambda.Compile();
            var r = l(a, b);
            Console.WriteLine(r);
        }
        /// <summary>
        /// ||
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        private void OrElse(bool a, bool b)
        {
            var left = Expression.Parameter(typeof(bool));
            var right = Expression.Parameter(typeof(bool));
            Expression exp = Expression.OrElse(left, right);
            Expression<Func<bool, bool, bool>> lambda = Expression.Lambda<Func<bool, bool, bool>>(exp, new ParameterExpression[] { left, right });
            var l = lambda.Compile();
            var r = l(a, b);
            Console.WriteLine(r);
        }

        /// <summary>
        /// -
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        private void Subtract(int a, int b)
        {
            var left = Expression.Parameter(typeof(int));
            var right = Expression.Parameter(typeof(int));
            Expression exp = Expression.Subtract(left, right);
            Expression<Func<int, int, int>> lambda = Expression.Lambda<Func<int, int, int>>(exp, new ParameterExpression[] { left, right });
            var l = lambda.Compile();
            var r = l(a, b);
            Console.WriteLine(r);
        }
        private void SubtractAssign(int a, int b)
        {
            var left = Expression.Parameter(typeof(int));
            var right = Expression.Parameter(typeof(int));
            Expression exp = Expression.SubtractAssign(left, right, this.GetType().GetMethod("Add2"));
            Expression<Func<int, int, int>> lambda = Expression.Lambda<Func<int, int, int>>(exp, new ParameterExpression[] { left, right });
            var l = lambda.Compile();
            var r = l(a, b);
            Console.WriteLine(r);
        }

        /// <summary>
        /// *
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        private void Multiply(int a, int b)
        {
            var left = Expression.Parameter(typeof(int));
            var right = Expression.Parameter(typeof(int));
            Expression exp = Expression.Multiply(left, right);
            Expression<Func<int, int, int>> lambda = Expression.Lambda<Func<int, int, int>>(exp, new ParameterExpression[] { left, right });
            var l = lambda.Compile();
            var r = l(a, b);
            Console.WriteLine(r);
        }
        private void MultiplyAssign(int a, int b)
        {
            var left = Expression.Parameter(typeof(int));
            var right = Expression.Parameter(typeof(int));
            Expression exp = Expression.MultiplyAssign(left, right, this.GetType().GetMethod("Add2"));
            Expression<Func<int, int, int>> lambda = Expression.Lambda<Func<int, int, int>>(exp, new ParameterExpression[] { left, right });
            var l = lambda.Compile();
            var r = l(a, b);
            Console.WriteLine(r);
        }
        /// <summary>
        /// /
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        private void Divide(int a, int b)
        {
            var left = Expression.Parameter(typeof(int));
            var right = Expression.Parameter(typeof(int));
            Expression exp = Expression.Divide(left, right);
            Expression<Func<int, int, int>> lambda = Expression.Lambda<Func<int, int, int>>(exp, new ParameterExpression[] { left, right });
            var l = lambda.Compile();
            var r = l(a, b);
            Console.WriteLine(r);
        }
        /// <summary>
        /// a/=b
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        private void DivideAssign(int a, int b)
        {
            var left = Expression.Parameter(typeof(int));
            var right = Expression.Parameter(typeof(int));
            Expression exp = Expression.DivideAssign(left, right, this.GetType().GetMethod("Add2"));
            Expression<Func<int, int, int>> lambda = Expression.Lambda<Func<int, int, int>>(exp, new ParameterExpression[] { left, right });
            var l = lambda.Compile();
            var r = l(a, b);
            Console.WriteLine(r);
        }
        /// <summary>
        /// --
        /// </summary>
        /// <param name="a"></param>
        private void Decrement(int a)
        {
            var left = Expression.Parameter(typeof(int));
            Expression exp = Expression.Decrement(left);
            Expression<Func<int, int>> lambda = Expression.Lambda<Func<int, int>>(exp, new ParameterExpression[] { left });
            var l = lambda.Compile();
            var r = l(a);
            Console.WriteLine(r);
        }
        /// <summary>
        /// ++
        /// </summary>
        /// <param name="a"></param>
        private void Increment(int a)
        {
            var left = Expression.Parameter(typeof(int));
            Expression exp = Expression.Increment(left);
            Expression<Func<int, int>> lambda = Expression.Lambda<Func<int, int>>(exp, new ParameterExpression[] { left });
            var l = lambda.Compile();
            var r = l(a);
            Console.WriteLine(r);
        }
        /// <summary>
        /// >
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        private void LessThan(int a, int b)
        {
            var left = Expression.Parameter(typeof(int));
            var right = Expression.Parameter(typeof(int));
            Expression exp = Expression.LessThan(left, right);
            Expression<Func<int, int, bool>> lambda = Expression.Lambda<Func<int, int, bool>>(exp, new ParameterExpression[] { left, right });
            var l = lambda.Compile();
            var r = l(a,b);
            Console.WriteLine(r);
        }
        /// <summary>
        /// ??
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        private void Coalesce(int? a, int b)
        {
            var left = Expression.Parameter(typeof(int?));
            var right = Expression.Parameter(typeof(int));

            var right2 = Expression.Assign(right, Expression.Default(typeof(int)));
            Expression exp = Expression.Coalesce(left, right2);
            Expression<Func<int?, int, int>> lambda = Expression.Lambda<Func<int?, int, int>>(exp, new ParameterExpression[] { left, right });
            var l = lambda.Compile();
            var r = l(a, b);
            Console.WriteLine(r);
        }

        public static bool IsFalse(bool flag){
           return false;
        }
        /// <summary>
        /// is
        /// </summary>
        private void Is()
        {
            var v1 = Expression.Parameter(typeof(bool));

            var v11 = Expression.Assign(v1,Expression.Constant(true));
            var v2 = Expression.IsFalse(v1, this.GetType().GetMethod("IsFalse"));
            Expression exp = Expression.IsFalse(v2);
            var v3=Expression.TypeIs(Expression.Constant(new List<int>()),typeof(IList<int>));
            Expression<Func<bool,bool>> lambda = Expression.Lambda<Func<bool,bool>>(exp, new ParameterExpression[] {v1 });
            var l = lambda.Compile();
            var r = l(true);
            Console.WriteLine(r);
            Expression<Func<bool>> lambda2 = Expression.Lambda<Func<bool>>(v3);
            var l2 = lambda2.Compile();
            Console.WriteLine(l2());
        }
        /// <summary>
        /// if
        /// </summary>
        private void If()
        {
            var v1 = Expression.Variable(typeof(int),"a");
            var v11 = Expression.Assign(v1, Expression.Constant(10));
            var v2 = Expression.GreaterThan(v11, Expression.Constant(9));
            Expression exp = Expression.IfThen(v2,Expression.Call(typeof(Console).GetMethod("WriteLine",new Type[]{typeof(int)}),v1));
            Expression exp2 = Expression.Block(new[]{v1},exp);
            Expression<Action> lambda = Expression.Lambda<Action>(exp2, new ParameterExpression[] { });
            var l = lambda.Compile();
            l();
        }

        /// <summary>
        /// if else
        /// </summary>
        private void IfElse()
        {
            var v1 = Expression.Variable(typeof(int), "a");
            var v11 = Expression.Assign(v1, Expression.Constant(10));
            var v2 = Expression.GreaterThan(v11, Expression.Constant(9));
            Expression exp = Expression.IfThenElse(v2, Expression.Call(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }), Expression.Constant("True")), Expression.Call(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }), Expression.Constant("False")));
            Expression exp2 = Expression.Block(new[] { v1 }, exp);
            Expression<Action> lambda = Expression.Lambda<Action>(exp2, new ParameterExpression[] { });
            var l = lambda.Compile();
            l();
        }

        /// <summary>
        /// trueTest?ifTrue:ifFalse;
        /// </summary>
        private void Condition()
        {
            var v1 = Expression.Variable(typeof(int), "a");
            var v11 = Expression.Assign(v1, Expression.Constant(10));
            var v2 = Expression.GreaterThan(v1, Expression.Constant(9));
            Expression exp = Expression.Condition(v2, Expression.Call(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }), Expression.Constant("True")), Expression.Call(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }), Expression.Constant("False")));
            Expression exp2 = Expression.Block(new[] { v1 },v11, exp);
            Expression<Action> lambda = Expression.Lambda<Action>(exp2, new ParameterExpression[] { });
            var l = lambda.Compile();
            l();
        }
        /// <summary>
        /// switch
        /// </summary>
        /// <param name="i"></param>
        private void Switch(int i)
        {
            var par = Expression.Parameter(typeof(int));
            var target = Expression.Label(typeof(int),"a");
            var exp = Expression.Switch(par, Expression.Break(target, Expression.Constant(-5)), Expression.SwitchCase(Expression.Break(target, par), Expression.Constant(1)));
            var lbl = Expression.Label(target, Expression.Constant(0));
            var block = Expression.Block(exp,lbl);
            Expression<Func<int, int>> lambda = Expression.Lambda<Func<int, int>>(block, new ParameterExpression[] { par });
            var l = lambda.Compile();
            Console.WriteLine(l(i));
        }
        /// <summary>
        /// while(true){}
        /// </summary>
        /// <param name="i"></param>
        private void Loop(int i)
        {
            var par = Expression.Parameter(typeof(int));
            var ret = Expression.Variable(typeof(int), "ret");
            var v11 = Expression.Assign(ret, Expression.Constant(0));
            var lbl = Expression.Label(typeof(int));
            var lbl2 = Expression.Label(lbl,Expression.Constant(0));
            var block1 = Expression.Block(Expression.AddAssign(ret,par),Expression.SubtractAssign(par,Expression.Constant(2)));
            var condition = Expression.IfThenElse(Expression.GreaterThan(par, Expression.Constant(0)),block1, Expression.Break(lbl, ret));
            var block2 = Expression.Block(new[] { ret }, v11, Expression.Loop(condition), lbl2);// Expression.Block(new[] { ret }, v11, Expression.Loop(condition,lbl))  可以達到一樣的效果
            Expression<Func<int, int>> lambda = Expression.Lambda<Func<int, int>>(block2, new ParameterExpression[] { par });
            var l = lambda.Compile();
            Console.WriteLine(l(i));
        }

        /// <summary>
        /// as
        /// </summary>
        private void TypeAs()
        {
            Expression s = Expression.Constant(1);
            var t=Expression.TypeAs(s, typeof(object));
            var call = Expression.Call(typeof(Console).GetMethod("WriteLine", new[] { typeof(int) }), Expression.Unbox(t, typeof(int)));
            Expression<Action> lambda = Expression.Lambda<Action>(call);
            var l=lambda.Compile();
            l();
        }

        /// <summary>
        /// 強轉  class定義TypeConverter,TypeConverterAttribute
        /// </summary>
        private void Convert()
        {
            Expression s = Expression.Constant(7.5);
            var t = Expression.Convert(s, typeof(int));
            var call = Expression.Call(typeof(Console).GetMethod("WriteLine", new[] { typeof(int) }),t);
            Expression<Action> lambda = Expression.Lambda<Action>(call);
            var l = lambda.Compile();
            l();
        }

        /// <summary>
        /// %
        /// </summary>
        private void Modulo()
        {
            Expression s1 = Expression.Constant(7);
            Expression s2 = Expression.Constant(4);
            var t = Expression.Modulo(s1,s2);

            Expression<Func<int>> lambda = Expression.Lambda<Func<int>>(t);
            var l = lambda.Compile();
            Console.WriteLine(l());
        }

        /// <summary>
        /// new
        /// </summary>
        private void New()
        {
            Expression s = Expression.Constant(7);
            var t = Expression.New(typeof(T));
            var call = Expression.Call(t, typeof(T).GetMethod("Test"));
            Expression<Action> lambda = Expression.Lambda<Action>(call);
            var l = lambda.Compile();
            l();
        }

        /// <summary>
        /// 初始化數組對象new int[]{7}
        /// </summary>
        private void NewArray()
        {
            Expression s = Expression.Constant(7);
            var t = Expression.NewArrayInit(typeof(int),s);
            var call = Expression.Call(t, typeof(int[]).GetProperty("Length").GetGetMethod());
            Expression<Func<int>> lambda = Expression.Lambda<Func<int>>(call);
            var l = lambda.Compile();
            Console.WriteLine(l());
        }

        /// <summary>
        /// new int[7]
        /// </summary>
        private void NewArrayBounds()
        {
            Expression s = Expression.Constant(7);
            var t = Expression.NewArrayBounds(typeof(int), s);
            var call = Expression.Call(t, typeof(int[]).GetProperty("Length").GetGetMethod());
            Expression<Func<int>> lambda = Expression.Lambda<Func<int>>(call);
            var l = lambda.Compile();
            Console.WriteLine(l());
        }
        /// <summary>
        /// new List<int>(){5}
        /// </summary>
        private void ListInit()
        {
            Expression s = Expression.Constant(5);
            var lst = Expression.New(typeof(List<int>));
            var t = Expression.ListInit(lst,s);
            var call = Expression.Call(t, typeof(List<int>).GetProperty("Count").GetGetMethod());
            Expression<Func<int>> lambda = Expression.Lambda<Func<int>>(call);
            var l = lambda.Compile();
            Console.WriteLine(l());
        }
        /// <summary>
        /// var s=new S();s.Ids.Add(5);s.Ids.Add(7);
        /// </summary>
        private void ListBind()
        {
            Type s = typeof(S);
            var n=Expression.New(s);
            var ids=s.GetProperty("Ids");
            var l=typeof(List<int>);
            var n2 = Expression.New(l);
            var e1 = Expression.ElementInit(l.GetMethod("Add"), Expression.Constant(5));
            var e2 = Expression.ElementInit(l.GetMethod("Add"
              
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • WebApi框架,可分為三層:托管層、消息處理程式托管層、控制器處理層。 一、托管層: 即Host,是WebAPI宿主,如:控制台,Windows服務等。 寄宿方式。 1、定製托管。 2、自托管。 3、Web托管 Owin寄宿 ,如Katana, 在一個Owin相容的伺服器上建立一個WebApi層, ...
  • MD5簡介: MD5的全稱是Message-Digest Algorithm 5,在90年代初由MIT的電腦科學實驗室和RSA Data Security Inc發明,經MD2、MD3和MD4發展而來。MD5將任意長度的“位元組串”變換成一個128bit的大整數,並且它是一個不可逆的字元串變換演算法。 ...
  • ASP.NET支持以下驗證控制項 RequiredFieldValidator(非空驗證) 確保用戶沒有跳過輸入控制項。RequiredFieldValidator控制項可以與文本框綁定在一起,以便強制用戶對文本框進行輸入。使用選擇控制項,例如,對於下拉框控制項和單選按鈕,RequiredFieldValid ...
  • 分類:C#、VS2015 創建日期:2016-06-23 使用教材:(十二五國家級規劃教材)《C#程式設計及應用教程》(第3版) 一、要點 該例子屬於高級技術中的基本用法。對於初學者來說這是難點(難在還沒有學習第13章WPF相關的繪圖技術),因此,這裡的關鍵是理解設計思路,而不是一開始就陷於細節的實... ...
  • 晚上無聊寫了個二叉樹(圖)的廣度和深度遍歷演算法,演算法本身很簡單,但是如何做到通用呢,一下代碼是我的設計,請大家幫忙看看有什麼問題,我自己感覺有問題就是不知道具體什麼問題 單元測試代碼: [TestClass] public class BreadthVisitorTest { [TestMethod ...
  • 寫代碼出身的我們經常需要使用一些簡單 但是不是規則圖形的Path 但限於美工功底有限 不知道怎麼去畫 下麵我告訴大家一些簡單的小技巧 用代碼來畫Path 個人還是比較喜歡用代碼 因為數值控制的更精細 MSDN告訴我們,Path可以用這些形狀繪製: ArcSegment 類 表示兩點之間的一條橢圓弧。 ...
  • 1.結構體裡面是否可以有屬性? 可以有屬性。實測代碼以及截圖。 In C#, we can use the following statement to convert a string s to an integer num 124 A.int num = Convert.ToInt32(s); ...
  • 幫同學搞個課程設計winform連接sqlserver2005 具體方法: .添加App.config文件 2.在App.config文件中添加節點 3.在項目Reference中添加引用 System.configuration 在文件中 添加引用 using System.configurati ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...