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



    }

    }
  • 相关阅读:
    插入排序
    python -- 给电视剧重命名
    程序员你为什么迷茫?
    如何把自己打造成技术圈的 papi 酱
    GitHub中国区前100名到底是什么样的人?
    Python+opencv 图像拼接
    VS2015 新Web项目(C#6)出现CS1617错误的解决
    .Net Task<T>的一种比较神奇的卡死情况(Wait/Result卡死, await能得到结果)
    Xamarin Android自学和实践步骤
    跨过几个坑,终于完成了我的第一个Xamarin Android App!
  • 原文地址:https://www.cnblogs.com/rhythmK/p/2241812.html
Copyright © 2011-2022 走看看