zoukankan      html  css  js  c++  java
  • C#通过函数名字符串执行相应的函数

    如果代码中函数过多,那么通过函数名字符串执行相应的函数会更加方便,也会使代码更为简单。

    在C#中,通过函数名字符串执行相应的函数这项功能是在System. Reflection命名空间中实现的,使用的函数为GetMethod。若要使用此功能只需如下三步。

     

    一.GetMethod函数定义在虚基类Type类中,在使用函数前应先获取一个Type对象,代码为:

    Type t=typeof(Program); //括号中的为所要使用的函数所在的类的类名。

     

    二.通过对象t便可以使用GetMethod函数了,代码如下:

    MethodInfo mt = t.GetMethod("aabbcc",BindingFlags.Static);

    注:

    GetMethod函数有6个重载函数,其中常用的有2个。

    publicMethodInfo GetMethod(stringname)

    publicMethodInfo GetMethod(stringname,BindingFlagsbindingAttr)

    name为所要使用的函数名    bindingAttr为搜索范围

    第一个函数对 name的搜索区分大小写。搜索范围包括公共静态方法和公共实例方法。若搜索的函数不在此范围内,则应使用第二个函数。

    若成功搜索到函数,则返回非null值,否则返回非空值,在向下执行前应检查一下返回值,否则会报错。

     

    三.获取到非空的MethodInfo类的实例mt后便可执行所要的函数了。

    string str = (string)mt.Invoke(null,newobject[] { "1234567890123"    });

    注:

    Invoke函数的原型如下:

    publicObject Invoke(Objectobj,Object[]parameters)

    第一个参数为对其调用方法或构造函数的对象。如果方法是静态的,则应为null,否则必需给出一个实例,若在同一类中调用,则可指定为this。

    第二个参数为调用的方法的参数列表。这是一个对象数组,这些对象与要调用的方法或构造函数的参数具有相同的数量、顺序和类型。如果没有任何参数,则 parameters应为nullNothingnullptrnull引用。

    函数的返回值便为所调用的函数的返回值,若无返回值,则为null。在获取返回值前应进行强制类型转换。

     

    四.示例如下:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Reflection;
    namespace Practice { class Program { static void Main(string[] args) { Type t = typeof(Program);//括号中的为所要使用的函数所在的类的类名。 MethodInfo mt = t.GetMethod("aabbcc",BindingFlags.Static); if (mt == null) { Console.WriteLine("没有获取到相应的函数!!"); } else { string str = (string)mt.Invoke(null,newobject[] { "1234567890123" }); Console.WriteLine(str); } Console.ReadKey(); } private static string aabbcc(string abc) { return abc; } } }

      

  • 相关阅读:
    Ubuntu 16 安装redis客户端
    crontab 参数详解
    PHP模拟登录发送闪存
    Nginx配置端口访问的网站
    Linux 增加对外开放的端口
    Linux 实用指令之查看端口开启情况
    无敌的极路由
    不同的域名可以指向同一个项目
    MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error
    Redis 创建多个端口
  • 原文地址:https://www.cnblogs.com/mapstar/p/13718182.html
Copyright © 2011-2022 走看看