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();
    }



    }

    }
  • 相关阅读:
    vmware中三种网络连接方式
    【史上最全面经】各岗位汇总目录
    史上最全2019届秋招备战攻略
    程序员常用软件
    经典大数据面试题
    春招实习终于结束啦
    Java程序员自我介绍
    java一些面试题
    收割大厂offer需要具备的条件
    triangular distribution
  • 原文地址:https://www.cnblogs.com/rhythmK/p/2241812.html
Copyright © 2011-2022 走看看