//获取类型。
//如果当string表示的目标类型不在当前程序集中,则运行时Type.GetType会返回null。解决 的办法是:首先加载目标程序集,然后再使用Assembly.GetType方法来获取类型。
public virtual Type GetType(string name);
Type.GetConstructor Method (System) | Microsoft Docs
//Gets a specific constructor of the current Type 获取当前类的构造函数, Type[] types 用来支持不同入参的构造函数
public ConstructorInfo GetConstructor(Type[] types);
//加载相关的dll程序集
public static Assembly Load(string assemblyString);
Type.GetConstructor Method (System) | Microsoft Docs
调用由具有指定参数的实例反映的构造函数
public object Invoke (object?[]? parameters);
简单版本:
using System;
using System.Text;
using System.Reflection;
using System.Linq;
class Test1
{
public static void Main()
{
Type type = typeof(StringBuilder);
Type[] argTypes = new Type[] { typeof(System.String), typeof(System.Int32) };
ConstructorInfo cInfo = type.GetConstructor(argTypes);
object[] argVals = new object[] { "Some string", 30 };
// Create the object and cast it to StringBuilder.
StringBuilder invoke = (StringBuilder)cInfo.Invoke(argVals);
StringBuilder direct = new StringBuilder("Some string", 30);
if (invoke.Equals(direct)) {
Console.WriteLine("Expected");
}
}
}
程序集进阶
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
class Test3
{
public static void GetNetjson()
{
Assembly helperAssembly;
string assemblyName = "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed";
try
{
//完成相关dll的load
helperAssembly = Assembly.Load(assemblyName);
}
catch (FileNotFoundException)
{
Console.WriteLine("Cannot load assembly {0}", assemblyName); // do not localize
throw new FileNotFoundException(assemblyName);
}
string typeName = "Newtonsoft.Json.Converters.DataSetConverter";
//在 Newtonsoft.Json的程序集中获取到DataSetConverter类型
Type helperType = helperAssembly.GetType(typeName);
if (helperType == null)
{
Console.WriteLine("Cannot load type {0}", typeName); // do not localize
throw new Exception("FailedToCreateType");
}
//选择了DataSetConverter参数为空的构造函数
ConstructorInfo cinfo = helperType.GetConstructor(new Type[] { });
if (cinfo == null)
{
Console.WriteLine("Cannot get constructor info"); // do not localize
throw new Exception("FailedToCreateCinfo");
}
//回调构造函数,生成DataSetConverter
Object result = cinfo.Invoke(null);
if (result == null)
{
Console.WriteLine("Cannot instantiate object"); // do not localize
throw new Exception("FailedToCreateObject");
}
}
}