最新文章
泰课新年学课蛇来运转欢度春节活动
02-01 20:25
共庆2024圣诞、元旦泰课双蛋活动
12-16 10:21
泰课共庆75周年国庆活动!
10-05 21:24
暑假双月联动学习计划 7月15 - 8月21日
07-14 23:09
泰课在线劳动光荣,勤学快乐之五月勤学季活动
04-30 21:19
2024年青春绽放开学季活动
03-11 13:01
Activator.CreateInstance使用中的参数传入
1. 定义接口
首先,我们定义一个接口 ICustom,该接口包含一个 Get 方法。以下是接口的代码:
public interface ICustom
{
string Get();
}
2. 创建接口的实现类
接下来,创建接口 ICustom 的两个实现类 CustomA 和 CustomB。这两个类均包含 SendTimeout 和 Address 属性,并且都有一个带两个参数的构造函数,用于初始化这些属性。在动态调用时,我们会传入这两个参数。
CustomA 类
public class CustomA : ICustom
{
public string SendTimeout { get; set; }
public string Address { get; set; }
public CustomA(string sendTimeout, string address)
{
this.SendTimeout = sendTimeout;
this.Address = address;
}
public string Get()
{
return string.Concat("CustomA ", SendTimeout, " ", Address);
}
}
CustomB 类
public class CustomB : ICustom
{
public string SendTimeout { get; set; }
public string Address { get; set; }
public CustomB(string sendTimeout, string address)
{
this.SendTimeout = sendTimeout;
this.Address = address;
}
public string Get()
{
return string.Concat("CustomB ", SendTimeout, " ", Address);
}
}
3. 应用 Activator.CreateInstance 动态调用指定的 ICustom 实现
下面的代码展示了如何使用 Activator.CreateInstance 方法动态创建 ICustom 接口的实现类实例,并传入构造函数所需的参数。
ICustom iCustom = null;
Type type = Type.GetType("CSDN.Profile.Statistic.WebTest.CustomA,CSDN.Profile.Statistic.WebTest");
if (type != null)
{
iCustom = (ICustom)Activator.CreateInstance(type, new object[] { "00:00:03", "net.pipe://localhost/StatisticProvider" });
}
string str = iCustom.Get();
Response.Output.Write(str);
运行上述代码后,返回的结果是 CustomA 00:00:03 net.pipe://localhost/StatisticProvider,这表明我们已经成功通过配置 type 动态构建了一个对应的接口实例。
C# 中 Activator.CreateInstance() 方法用法介绍
Activator 类
Activator 类包含特定的方法,用于在本地或从远程创建对象类型,或获取对现有远程对象的引用。在 C# 的类工厂中,我们可以使用该类的方法动态创建类的实例。
Activator.CreateInstance 方法的两种重载形式
- 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); object[] objParam = { /* 传入的参数 */ }; result = Activator.CreateInstance(typeofControl, objParam);这两种方法的主要区别在于,前者用于创建无参数的构造方法对应的类实例,而后者用于创建有参数的构造函数对应的类实例。
动态使用外部 DLL 中的类实例
在动态创建实例时,如果需要使用外部应用的 DLL 中的类实例,则需要进行反编译操作,此时可以使用 Reflection 命名空间下的 Assembly 类。以下是示例代码:
object result = null;
Type typeofControl = null;
Assembly tempAssembly;
tempAssembly = Assembly.LoadFrom(vDllName);
typeofControl = tempAssembly.GetType(vFullClassName);
object[] objParam = { /* 传入的参数 */ };
result = Activator.CreateInstance(typeofControl, objParam);
上述代码通过 Assembly.LoadFrom 方法载入 DLL,再根据类的全路径获取类类型,最后使用 Activator.CreateInstance 方法创建类实例。