Activator.CreateInstance使用中的参数传入

2020年01月23日 11:04 0 点赞 0 评论 更新于 2025-11-21 21:30

1. 定义接口

首先,我们定义一个接口 ICustom,该接口包含一个 Get 方法。以下是接口的代码:

public interface ICustom
{
string Get();
}

2. 创建接口的实现类

接下来,创建接口 ICustom 的两个实现类 CustomACustomB。这两个类均包含 SendTimeoutAddress 属性,并且都有一个带两个参数的构造函数,用于初始化这些属性。在动态调用时,我们会传入这两个参数。

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 方法的两种重载形式

  1. Activator.CreateInstance (Type):用于创建无参数构造函数的类实例。
    object result = null;
    Type typeofControl = null;
    typeofControl = Type.GetType(vFullClassName);
    result = Activator.CreateInstance(typeofControl);
    
  2. 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 方法创建类实例。