反射创建类实例

皇姑雪糕 2012-03-01 11:21:57
我使用工厂模式创建了若干方法例如

public ClassFactory
{
public ReturnClass Create(ClassA a) {....}
public ReturnClass Create(ClassB b) {....}
}

我只有在运行时才能得到ClassA或者是ClassB的类名的字符串形式,现在我有如下代码

ClassFactory cf = new ClassFactory();
string paramName = GetParamName(); //paramName 就是“ClassA”或者“ClassB”

//.....这段不会写啊
//得到ClassA或ClassB的实例a

ReturnClass rc = cf.Create(a);
...全文
138 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Caney 2012-03-01
  • 打赏
  • 举报
回复
object result = null;
Type type = Type.GetType(className);
result = Activator.CreateInstance(type);
qxyywy 2012-03-01
  • 打赏
  • 举报
回复

/// <summary>
/// This class is implemented following the Abstract Factory pattern to create the BLL implementation
/// specified from the configuration file
/// </summary>
public sealed class DataAccess
{

// Look up the BLL implementation we should be using
private static readonly string path = "*****.BLL";
private static readonly Assembly bllAssembly = null;

static DataAccess()
{
bllAssembly = Assembly.Load(path);
}

private DataAccess() { }

/// <summary>
/// 创建业务逻辑对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T GetBll<T>()
{
Type type = typeof(T);
return (T)bllAssembly.CreateInstance(type.Namespace.Replace("IBLL", "BLL") + "." + type.Name.Substring(1));
}
}

110,549

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧