Provider提供程序模型中,常常使用反射工厂来获得配置的实例,虽然代码比较简单,但是却也必不可少。
这里用添加了泛型这一特性,虽然性能不见得有什么提高(用不用泛型都会有一个类型转换),但是用了就好像给人一种性能提高了的感觉 ^_^ .
using System.Reflection;
namespace Helper.Reflection
{
/// <summary>
/// 类工厂
/// </summary>
static class ClassFactory
{
/// <summary>
/// 创建类实例的方法,程序集名可以与类命名空间不同
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="assemblyName">程序集名</param>
/// <param name="className">完全类名</param>
/// <returns>类的实例</returns>
public static T CreateInstance<T>(string assemblyName, string className)
{
return (T)Assembly.Load(assemblyName).CreateInstance(className);
}
/// <summary>
/// 创建类实例的方法,程序集名即为类命名空间
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="className">完全类名</param>
/// <returns>类的实例</returns>
public static T CreateInstance<T>(string className)
{
string assemblyName = className.Substring(0, className.LastIndexOf('.'));
return (T)Assembly.Load(assemblyName).CreateInstance(className);
}
}
}
namespace Helper.Reflection
{
/// <summary>
/// 类工厂
/// </summary>
static class ClassFactory
{
/// <summary>
/// 创建类实例的方法,程序集名可以与类命名空间不同
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="assemblyName">程序集名</param>
/// <param name="className">完全类名</param>
/// <returns>类的实例</returns>
public static T CreateInstance<T>(string assemblyName, string className)
{
return (T)Assembly.Load(assemblyName).CreateInstance(className);
}
/// <summary>
/// 创建类实例的方法,程序集名即为类命名空间
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="className">完全类名</param>
/// <returns>类的实例</returns>
public static T CreateInstance<T>(string className)
{
string assemblyName = className.Substring(0, className.LastIndexOf('.'));
return (T)Assembly.Load(assemblyName).CreateInstance(className);
}
}
}