C# 使用反射技术加载程序集(Assembly)并利用Activator创建实例
在C#语言编程中可以使用Assembly的反射技术加载程序集或获取当前运行的程序集,进而利用Activator使用类的完全名称创建对应的实例。
使用Assembly加载程序集: Assembly.Load(rootPath + "Qidian.SEO.Baidu.Station.dll");
string rootPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; var assembly = Assembly.Load(rootPath + "Qidian.SEO.Baidu.Station.dll");
Assembly加载运行中的程序集: Assembly assembly = Assembly.GetExecutingAssembly();
Assembly assembly = Assembly.GetExecutingAssembly();
Assembly获取所有程序集: AppDomain.CurrentDomain.GetAssemblies();
var assemblys = AppDomain.CurrentDomain.GetAssemblies();
从全部程序集种获取对应名称的程序集
var assemblys = AppDomain.CurrentDomain.GetAssemblies();
var assembly = assemblys.Where(p => "Qidian.SEO.Baidu.Station.Model.UserInfo".Contains(p.GetName().Name)).FirstOrDefault();
Type type = assembly.GetType("Qidian.SEO.Baidu.Station.Model.UserInfo");
var instance = Activator.CreateInstance(type).GetType();
var bb = OrmProvider.Query(instance);
Assembly获取引用程序集
public static class Extents
{
public static List<Assembly> GetReferanceAssemblies(this AppDomain domain)
{
var list = new List<Assembly>();
domain.GetAssemblies().ForEach(i =>
{
GetReferanceAssemblies(i, list);
});
return list;
}
static void GetReferanceAssemblies(Assembly assembly, List<Assembly> list)
{
assembly.GetReferencedAssemblies().ForEach(i =>
{
var ass = Assembly.Load(i);
if (!list.Contains(ass))
{
list.Add(ass);
GetReferanceAssemblies(ass, list);
}
});
}
}
Activator创建实例Activator.CreateInstance(type);
Type type = assembly.GetType("Qidian.SEO.Baidu.Station.UserInfo");
var instance = Activator.CreateInstance(type);