【发布时间】:2011-11-18 10:52:03
【问题描述】:
我的代码是
type = Type.GetType(key);
我传递的键是命名空间限定名。
我的代码在 BusinessLayer 中。我正在创建 DataAccessLayer 的一个实例。 DataAccessLayer 引用已添加到 BusinessLayer。
我收到的错误是 “无法从程序集 'BusinessLayer, Version=1.9.3.0, Culture=neutral, PublicKeyToken=null' 加载类型 'Catalyst.DAL.ExamDAO.CExamDAO'。”.
我应该怎么做才能明确指定该类来自 DataAccessLayer ?
键值是“Catalyst.DAL.ExamDAO.CExamDAO”
编辑:
我的实际代码是
public static object getClassInstance(string key, params object[] constructorArgs)
{
string assemblyPath = null;
string customClassName = null;
DataSet objDataset = getAssemblyInfo(key);
if (objDataset != null && objDataset.Tables.Count > 0 && objDataset.Tables[0].Rows.Count > 0)
{
assemblyPath = objDataset.Tables[0].Rows[0]["ACA_ASSEMBLY_PATH"].ToString();
customClassName = objDataset.Tables[0].Rows[0]["ACA_CLASS_NAME"].ToString();
}
Assembly assembly;
Type type;
if (assemblyPath != null && assemblyPath != string.Empty)
{
assembly = Assembly.LoadFile(assemblyPath);
type = assembly.GetType(customClassName);
}
else // if no customisation
{
type = Type.GetType(key);
}
object classInstance = constructorArgs == null ? Activator.CreateInstance(type) : Activator.CreateInstance(type, constructorArgs);
if (classInstance == null) throw new Exception("broke");
return classInstance;
}
如果没有自定义,我正在尝试加载默认类。方法在 BO 中。 如果我将密钥作为任何 Bo 类型的命名空间限定名称传递,它将转换。但是DAO类型它不会
【问题讨论】:
-
你为什么这样做而不是
new CExamDAO()?如果确实“将 DataAccessLayer 引用添加到 BusinessLayer”,那么您应该没有理由不能使用new运算符。或者,如果您真的只是想要一个类型引用,那么typeof(CExamDAO) -
给我们“key”的文本值。
-
@亚当拉尔夫。实际上我需要在自定义程序集和默认程序集之间切换。我尽力把代码放在这里。
-
@xanatos 我放了键值
标签: c# class reflection activator gettype