C#,将字符串变量转换为类变量

Kun*_*esh 3 c# reflection constructor class

我的功能如下.

public static object getClassInstance(string key, object constructorParameter)
{
         // body here
}
Run Code Online (Sandbox Code Playgroud)

键变量将具有我的类名.我需要返回类的新实例.如果constructorParm为null,那么我需要使用默认构造函数else传递构造函数参数来加载该类.我该怎么做呢 ?

添加:

我写了这样的代码

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

传递给函数的键是"CReportBO".CReportBO可在函数范围内访问.但是在//如果没有自定义部分(即type = Type.GetType(key)),则返回null.怎么了 ?

Mar*_*ell 7

如果在核心程序集或调用程序集中key程序集限定命名空间限定,则:

Type type = Type.GetType(key);
return constructorParameter == null ? Activator.CreateInstance(type)
          : Activator.CreateInstance(type, constructorParameter);
Run Code Online (Sandbox Code Playgroud)

不过,我想知道:

public static object getClassInstance(string key, params object[] args)
Run Code Online (Sandbox Code Playgroud)

更灵活,允许:

Type type = Type.GetType(key);
return Activator.CreateInstance(type, args);
Run Code Online (Sandbox Code Playgroud)

用法如下:

object o = getClassInstance(key); // uses default constructor
object o = getClassInstance(key, null); // passes null to single parameter
object o = getClassInstance(key, 123, "abc"); // etc
Run Code Online (Sandbox Code Playgroud)