C# 反射,通过类名、方法名调用方法

转载自:https://www.cnblogs.com/coderJiebao/p/CSharp09.html

在 C# 代码中,有些时候只知道方法的名字(string),需要调用该方法,那么就需要用到 C# 的反射机制。下面是一个简单的 demo。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;

namespace Map
{
    class Test
    {
        public void Method() 
        {
            Console.WriteLine("Method无参数调用");
        }

        public void Method(string str)
        {
            Console.WriteLine("有一个参数调用成功,参数是"+ str);
        }

        public string  Method(string str1, string str2)
        {
            Console.WriteLine("有两个参数调用成功,参数是:" + str1+"第二个参数是:"+ str2);
            string className = this.GetType().FullName;
            return className;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string strClass = "Map.Test";//命名空间+类名
            string sreMethod = "Method";//方法名

            Type type;//存储类
            object obj;//存储类的实例

            type = Type.GetType(strClass);//通过类名获取同名类
            obj = System.Activator.CreateInstance(type);//创建实例

            MethodInfo method = type.GetMethod  (sreMethod, new Type[]{});//获取方法信息
            object[] parameters = null;
            method.Invoke(obj, parameters);//调用方法,参数为空

            method = type.GetMethod(sreMethod, new Type[] { typeof(string) });//获取方法信息
            parameters = new object[] { "你好" };
            method.Invoke(obj, parameters);//调用方法有参数

            method = type.GetMethod(sreMethod, new Type[] { typeof(string), typeof(string) });
            parameters = new object[] { "你好", "大熊" };
            string result = (string)method.Invoke(obj, parameters);
            Console.WriteLine("Method的返回值" + result);

            string ClassName = MethodBase.GetCurrentMethod().ReflectedType.FullName;
            Console.WriteLine("当前静态方法类名" + ClassName);

            Console.ReadKey();
        }
    }
}

需要注意的是,类名是命名空间+类名,不然会找不到类

另外补充:方法必须是public否则找不到,为null。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值