我有如下功能。C#,将字符串变量转换为类变量
public static object getClassInstance(string key, object constructorParameter)
{
// body here
}
关键变量将有我的班级名称。我需要返回该类的新实例。如果constructorParm为null,那么我需要使用默认构造函数加载类,否则传递构造函数参数。我该怎么做呢 ?
地址:
我写的代码一样传递给函数是 “CReportBO” 这
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可以在函数的范围内访问。但在/ /如果没有自定义部分(即type = Type.GetType(key)),类型返回我空。怎么了 ?
如果您想使用'null' *作为参数*; p –
i don hai ve dat条件的nw。但我会处理它。我如何处理为什么现有的情况? –
@Nithesh:请注意,您可以通过缩进四个空格来[将行格式化为代码](http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks)。编辑器工具栏中的“{}”按钮可以为您做到这一点。其他人在这个问题上为你做了,但下次你应该自己尝试。单击编辑器工具栏中的橙色问号以获取更多信息和格式化提示。 – outis