zoukankan      html  css  js  c++  java
  • Expression 常用方法

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Linq.Expressions;
    using System.Collections;
    using System.Data.Common;
    using System.Data;
    using System.Data.Linq;
    using System.Reflection;
    using System.Diagnostics;

    namespace ConsoleApp
    {

    public class Boy
    {
    public int UserID;
    public int Age;
    public string Name;
    public static string Move()
    {
    return string.Format("The Boy begin Move;");
    }

    public static int GetDoubbleNum(int num)
    {
    return num + num;
    }
    public Boy() { }


    public string Play(string objName)
    {
    return "Play the "+objName;
    }
    }



    class Program
    {
    static void Main(string[] args)
    {
    ParameterExpression boyParameter = Expression.Parameter(typeof(Boy), "boy");
    ParameterExpression intParameter = Expression.Parameter(typeof(Int32), "i");
    ParameterExpression strParameter = Expression.Parameter(typeof(string), "str");
    // 调用无参静态方法
    MethodInfo mInfo = typeof(Boy).GetMethod("Move");
    MethodCallExpression mcExp = Expression.Call(null, // 静态方法为null
    mInfo,
    new Expression[] { } // 静态方法 传入的参数类型 typeof(object)
    );
    var staticMethodNoPrameter = Expression.Lambda<Func<Boy, string>>(mcExp, boyParameter).Compile();


    // 调用有参静态方法
    mInfo = typeof(Boy).GetMethod("GetDoubbleNum");
    mcExp = Expression.Call(null,
    mInfo,
    new Expression[] { intParameter});
    var staticMethodHavePrameter = Expression.Lambda<Func<Boy,int, int>>(mcExp, boyParameter,intParameter).Compile();


    // 调用普通方法
    mInfo = typeof(Boy).GetMethod("Play");
    mcExp = Expression.Call(boyParameter,
    mInfo,
    new Expression[] { strParameter });
    var generalMethod = Expression.Lambda<Func<Boy, string, string>>(mcExp, boyParameter, strParameter).Compile();


    Boy boy = new Boy() { UserID = 10, Age = 18, Name = "Rhythmk" };

    Console.WriteLine("staticMethodNoPrameter:" + staticMethodNoPrameter(boy));
    Console.WriteLine("staticMethodHavePrameter:" + staticMethodHavePrameter(boy,12));
    Console.WriteLine("generalMethod:" + generalMethod(boy, "FootBoy"));

    /* 输出结果:
    * staticMethodNoPrameter:The Boy begin Move;
    * staticMethodHavePrameter:24
    * generalMethod:Play the FootBoy
    */

    Console.Read();
    }



    }

    }
  • 相关阅读:
    git stash错误小记
    PHP,Mysql根据经纬度计算距离并排序
    JS~字符串长度判断,超出进行自动截取(支持中文)
    Redis的三种启动方式
    Ubuntu 14.04 LTS下安装Google Chrome浏览器
    PHP-PHPExcel用法详解
    git设置log的别名 for hist log样式格式化
    Ubuntu系统下配置PHP支持SQLServer 2005
    Git命令图片版
    《一线架构师实践指南》读后感(二)
  • 原文地址:https://www.cnblogs.com/rhythmK/p/2241812.html
Copyright © 2011-2022 走看看