You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过字符串类名获取类型并创建类实例

仅通过类名字符串创建类实例的解决方案

一、先解决类型获取问题

Type.GetType()无法直接通过单纯类名(比如"Car")获取类型,它需要完整的类型标识——也就是「命名空间.类名」,如果类在外部程序集,还得加上程序集名称。

场景1:已知类的命名空间

直接传入完整类型名即可:

// 类在当前程序集时
Type type = Type.GetType("YourNamespace.Car");

// 类在外部程序集(比如程序集名为"VehicleAssembly")时
Type type = Type.GetType("YourNamespace.Car, VehicleAssembly");

场景2:仅知道类名,不知道命名空间

遍历目标程序集的所有类型,匹配类名:

// 遍历当前执行程序集
Type type = Assembly.GetExecutingAssembly().GetTypes()
    .FirstOrDefault(t => t.Name == "Car");

// 遍历所有已加载的程序集(适合跨程序集查找)
Type type = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(assembly => assembly.GetTypes())
    .FirstOrDefault(t => t.Name == "Car");

二、获取类型后创建实例

拿到Type对象后,有两种常用方式创建实例:

方式1:用Activator.CreateInstance(简单通用)

适合无参构造或参数明确的场景:

if (type != null)
{
    // 调用无参构造
    object instance = Activator.CreateInstance(type);
    // 安全转换为具体类型(也可以用as关键字避免强制转换异常)
    Car car = (Car)instance;

    // 调用带参数的构造(比如Car(string brand, int year))
    object paramInstance = Activator.CreateInstance(type, "Toyota", 2024);
    Car paramCar = (Car)paramInstance;
}

方式2:用ConstructorInfo(灵活可控)

适合需要指定构造函数(比如私有构造、重载构造)的场景:

if (type != null)
{
    // 获取无参构造
    ConstructorInfo noParamCtor = type.GetConstructor(Type.EmptyTypes);
    // 获取带指定参数的构造(比如string+int)
    ConstructorInfo paramCtor = type.GetConstructor(new[] { typeof(string), typeof(int) });

    // 调用构造创建实例
    if (noParamCtor != null)
    {
        object instance = noParamCtor.Invoke(null);
    }
    if (paramCtor != null)
    {
        object instance = paramCtor.Invoke(new object[] { "Honda", 2023 });
    }
}

额外注意

  • 如果要调用私有构造,需要添加绑定标记:
ConstructorInfo privateCtor = type.GetConstructor(
    BindingFlags.Instance | BindingFlags.NonPublic, 
    null, 
    Type.EmptyTypes, 
    null);
  • 类型转换时推荐用as关键字做安全转换,避免抛出强制转换异常:
Car car = instance as Car;
if (car != null)
{
    // 执行逻辑
}

内容的提问来源于stack exchange,提问作者AliOr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 01:20:22