我的功能如下。
public static object getClassInstance(string key, object constructorParameter)
{
// body here
}
关键变量将有我的类名。我需要返回类的新实例。如果 constructorParm 为 null,那么我需要使用传递的构造函数参数使用默认构造函数加载类。我该怎么做呢 ?
添加:
我是这样写代码的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Catalyst.BO.StudentProfileBO;
using Catalyst.BO.ReportBO;
using Catalyst.DAL.ReportDAO;
using System.Collections;
using System.Data;
namespace Catalyst.BO.Factory
{
public class CFactory
{
public static object getClassInstance(string key, params object[] constructorArgs)
{
string assemblyPath = null;
string customClassName = key.Substring(0, 1) + "Custom" + key.Substring(1);
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();
}
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;
}
}
}
传递给函数的键是“CReportBO”。 CReportBO 可在函数范围内访问。但是在//if no customization section (i.e type = Type.GetType(key) ) 中, type 返回 null 。怎么了?
最佳答案
如果 key
在核心程序集或调用程序集中是程序集限定或 namespace 限定,则:
Type type = Type.GetType(key);
return constructorParameter == null ? Activator.CreateInstance(type)
: Activator.CreateInstance(type, constructorParameter);
不过,我想知道,如果:
public static object getClassInstance(string key, params object[] args)
更灵活,允许:
Type type = Type.GetType(key);
return Activator.CreateInstance(type, args);
用法如:
object o = getClassInstance(key); // uses default constructor
object o = getClassInstance(key, null); // passes null to single parameter
object o = getClassInstance(key, 123, "abc"); // etc
关于C#,将字符串变量转换为类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7253601/