Reflection LateBinding

本文详细介绍了EarlyBinding和LateBinding的概念、优缺点及使用场景,并通过示例展示了如何在C#中实现LateBinding,包括获取程序集、创建Type、实例化对象、调用方法的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Early Binding & Late Binding
1.Early Binding 在 编译时能发现错误 ,Late Binding则有可能在运行时抛出异常
2.Early Binding 性能更好,因为Late Binding要加载程序集,创建类型,实例等
3.Use Late Binding only when working with an object that are not available at compile time.一般只对在编译时不能获取的对象采用Late Binding

using System;
using System.Reflection;

namespace ReflectionLateBind
{
    class Program
    {
        static void Main(string[] args)
        {
            //获取程序集
            Assembly excutingAssembly = Assembly.GetExecutingAssembly();
            //获取Type,相当于动态的创建一个class Customer
            Type customerType = excutingAssembly.GetType("ReflectionLateBind.Customer");
            //相当于创建一个Customer的实例,但是Customer类需要能够被访问,使用Activator类
            object customerInstance = Activator.CreateInstance(customerType);
            //创建方法
            MethodInfo getFullName = customerType.GetMethod("GetFullName");
            //方法参数
            string[] parameters = new string[2];
            parameters[0] = "James";
            parameters[1] = "Bond";

            //执行方法 getFullName.Invoke(object , object[] parameters)
            object fullName =  getFullName.Invoke(customerInstance, parameters);
            Console.WriteLine(fullName .ToString ());

        }
    }
    public class Customer
    {
        public string GetFullName(string firstName,string lastName)
        {
            return firstName + " " + lastName;
        }
    }
}

通常的几个步骤:

1.获取当前程序集
//Assembly executingAssembly = Assembly.GetExecutingAssembly()
2.创建Type,对象想要在runtime中获得的类型(eg.class)
// Type customerType = executingAssembly.GetType("命名空间.class名称");
3.获取实例 返回类型为object
// object customerInstance = Activator.CreateInstance(刚才创建的Type)
4.通过创建的Type来获取相应的方法,属性,构造函数等
// MethodInfo getFullName = customerType.GetMethod("对应的class名称中的方法名")
//方法参数用object[],调用时传入3中的对象,getFullName(customerInstance ,parameters)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值