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

标签 c# class reflection constructor

我的功能如下。

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/

相关文章:

java - Java嵌套静态类

reflection - 如何使用反射按名称获取包常量值?

arrays - 如何使用反射制作多维数组或 slice

java - 多个包裹对象中的反射

c# - StaticResource 标记扩展与 System.Windows.Application.FindResource

c# - 在 C# 中读取 Excel 文件时如何修复 "Not a legal OleAut date."?

c# - 如果结构包含 DateTime 字段,为什么 LayoutKind.Sequential 的工作方式不同?

javascript - javascript 的 unescape() 的 c# 等价物是什么?

c++ - 包括头文件(包括它们自己)

c++ - 在 C++ 中,定义一个非常简单的对象的最有效方法是什么