C#通过程序集动态实例化对象,并调用对象方法

在TestAssembly命名空间下创建一个Person类,结构如下:

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

namespace TestAssembly
{
    public class Person
    {
        public void Say ()
        {
            Console.WriteLine("Person Say!");
        }

        public void Say (string str)
        {
            Console.WriteLine("Person Say : " + str);
        }

        private void Eat ()
        {
            Console.WriteLine("Person Eat");
        }
    }
}

编译生成程序集,放到E盘.

新建项目,动态加载并使用TestAssembly.代码如下:

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

namespace UseAssembly
{
    class Program
    {
        static void Main(string[] args)
        {
            string namespaceName = "TestAssembly";
            string className = "Person";
            string methodName = "Say";
            string assemblyPath = @"E:\TestAssembly.exe";

            //加载程序集
            Assembly assem = Assembly.LoadFrom(assemblyPath);

            //获取Person类
            //Type personTp = assem.GetType(className); //null
            Type personTp = assem.GetType(namespaceName + "." + className);

            //创建对象
            object person = Activator.CreateInstance(personTp);

            //获取无参Say方法
            //MethodInfo sayWithoutPar = personTp.GetMethod(methodName);//不明确的匹配,引发异常
            MethodInfo sayWithoutPar = personTp.GetMethod(methodName, new Type[0]);
            sayWithoutPar.Invoke(person, null);

            //获取有参Say方法
            MethodInfo sayWithPar = personTp.GetMethod(methodName, new Type[] { typeof(string) });
            sayWithPar.Invoke(person, new object[] { "sayWithoutPar.Invoke" });
        }
    }
}

打印结果:

注意:

1.通过程序集获取指定类型时,GetType中的类名要指定命名空间,否则获取不到.

2.重载方法的获取,要在GetMethod中指定参数数量及类型,否则会引发异常.

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值