我的代码是
type = Type.GetType(key);
我传递的 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 中。 如果我将 key 作为它转换的任何 Bo 类型的 namespace 限定名称传递。但是 DAO 类型它不会
最佳答案
如果您知道它是什么类型将在 DataAccessLayer
中,那么我会尽可能简单地获得一个 Assembly
引用,例如
Assembly assembly = typeof(AnyPublicTypeWithinTargetAssembly).Assembly;
Type type = assembly.GetType(namespaceQualifiedTypeName);
另一种方法是将 Type.GetType
与程序集限定的 名称一起使用,但就指定类型名称而言,这更冗长。
关于c# - Type.GetType(string typeName) 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7441003/