zoukankan      html  css  js  c++  java
  • 将string转为同名类名,方法名。(c#反射)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace stringConvertClass
    {
        class test
        {
            public void Method()
            {
                Console.WriteLine("调用成功!");
            }

            public void Method(testcase)

            {

                 console.WriteLine(testcase.toString());

            }
        }
        class Program
        {
            public static void run(TestCase testcase)
            {

              string strClass = "stringConvertClass.test";  //命名空间+类名
              string strMethod = "Method";//方法名
              Type t; 
              object obj;

              t = Type.GetType(strClass);//通过string类型的strClass获得同名类“t”
              System.Reflection.MethodInfo method = t.GetMethod(strMethod);//通过string类型的strMethod获得同名的方法“method”
              obj = System.Activator.CreateInstance(t);//创建t类的实例 "obj"
              
                  method.Invoke(obj,null);//t类实例obj,调用方法"method"

               //上面的方法是无参的,下面是有参的情况.

              object[] objs = new object[]{testcase};

              method.Invoke(obj,objs );//t类实例obj,调用方法"method(testcase)"

            }
            static void Main(string[] args)
            {

                TestCase testcase = new TestCase();//自己定义的类
                run(testcase);
            }
        }
    }

  • 相关阅读:
    Cheatsheet: 2018 11.01 ~ 2019 02.28
    Cheatsheet: 2018 08.01 ~ 2018 10.31
    Cheatsheet: 2018 05.01 ~ 07.31
    Cheatsheet: 2018 04.01 ~ 04.30
    stb_image multiple definition of first defined here 多文件包含问题
    NanoPi arm架构下的程序 ./ 运行黑屏 Qt环境可运行
    opencv3.4.9 + armv7 + arm-linux-gnueabihf交叉编译
    NIVIDIA Tegra K1 QWT安装使用问题和解决办法
    7.17日报
    7.16日报
  • 原文地址:https://www.cnblogs.com/tsql/p/7986573.html
Copyright © 2011-2022 走看看