当前位置: 移动技术网 > IT编程>开发语言>c# > C#中Activator.CreateInstance()方法用法分析

C#中Activator.CreateInstance()方法用法分析

2019年07月18日  | 移动技术网IT编程  | 我要评论
本文实例讲述了c#中activator.createinstance()方法用法。分享给大家供大家参考。具体分析如下: activator 类 包含特定的方法,用以在本

本文实例讲述了c#中activator.createinstance()方法用法。分享给大家供大家参考。具体分析如下:

activator 类

包含特定的方法,用以在本地或从远程创建对象类型,或获取对现有远程对象的引用。

c#在类工厂中动态创建类的实例,所使用的方法为:

1. activator.createinstance (type)

2. activator.createinstance (type, object[])

两种方法区别仅为:创建无参数的构造方法和创建有参数的构造函数。

//activator.createinstance(type)
object result = null;
type typeofcontrol =null;
typeofcontrol = type.gettype(vfullclassname);
result = activator.createinstance(typeofcontrol);
//activator.createinstance(type,object[])
object result = null;
type typeofcontrol =null;
typeofcontrol = type.gettype(vfullclassname);
result = activator.createinstance(typeofcontrol, objparam);

但是在动态创建时,可能会动态使用到外部应用的dll中类的实例,则此时需要进行反编译操作,使用reflection命名控件下的assembly类。

//先使用assembly类载入dll,再根据类的全路径获取类

object result = null;
type typeofcontrol = null;
assembly tempassembly;
tempassembly = assembly.loadfrom(vdllname);
typeofcontrol = tempassembly.gettype(vfullclassname);
result = activator.createinstance(typeofcontrol, objparam);

希望本文所述对大家的c#程序设计有所帮助。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网