Linq的delegate表达式,Insus.NET觉得它封装得好,让开发时简化了很多代码,而且容易阅读与检索。

比如,我们需要计算优惠给客户金额,打85%折,可以这样写:
LINQ的Expression与delegate表达式_Expression

 

LINQ的Expression与delegate表达式_Compile_02LINQ的Expression与delegate表达式_Lambda_03
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;

namespace Insus.NET.Utilities
{
    public class Class2
    {
        public decimal Preferential(decimal amount)
        {
            return amount * (1 - 0.85m);  //amount - amount * 0.85m;
        }
    }
}
Source Code

 

应用方法:
LINQ的Expression与delegate表达式_Lambda_04

 

下面我们使用delegate委托来实现:
LINQ的Expression与delegate表达式_Lambda_05

运行结果:
LINQ的Expression与delegate表达式_Lambda_06

 

 

接下来,Insus.NET还想使用一个表达式树的类型Expression<TDelegate>实现:
LINQ的Expression与delegate表达式_linq_07

LINQ的Expression与delegate表达式_Compile_02LINQ的Expression与delegate表达式_Lambda_03
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;

namespace Insus.NET.Utilities
{
    public delegate decimal pref(decimal amount);

    public class Class2
    {
        //public decimal Preferential(decimal amount)
        //{
        //    return amount * (1 - 0.85m);  //amount - amount * 0.85m;
        //}

        // public pref Preferential11 = a => (a * (1 - 0.85m));

        static Expression<pref> expr = amount => (amount - amount * 0.85m);

        public pref Preferential2 = expr.Compile();

    }
}
Source Code

 

方法引用运行结果:
LINQ的Expression与delegate表达式_Expression_10