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

获取传入变量对应表类型时,tableType始终为null的问题

解决Type.GetType返回null的问题

核心原因

Type.GetType(item.TableName)返回null,大多是因为你只传入了类的简单名称,未包含完整的命名空间+类名——如果目标类型不在当前执行程序集或系统核心程序集(mscorlib)里,这个方法就找不到对应的类型。

另外也可能是以下情况:

  • item.TableName的拼写和实际类名不一致(C#大小写敏感)
  • 目标类型所在的程序集没有被当前应用加载

解决方法

1. 使用完整类型名称

确保item.TableName存储的是命名空间.类名的完整格式,比如实体类在YourApp.Entities命名空间下,TableName应为YourApp.Entities.User而非User。

如果无法修改存储的TableName,可在代码中拼接命名空间:

// 假设所有表对应实体类都在同一命名空间下
string fullTypeName = $"YourApp.Entities.{item.TableName}";
var tableType = Type.GetType(fullTypeName);

2. 指定程序集加载(类型不在当前程序集时)

若目标类型在其他程序集里,需在完整类型名后添加程序集名称(不含.dll后缀):

// 格式:命名空间.类名, 程序集名称
string fullTypeName = $"YourApp.Entities.{item.TableName}, YourApp.Data";
var tableType = Type.GetType(fullTypeName);

3. 遍历已加载程序集查找类型

如果不确定类型所在程序集,可遍历当前应用已加载的所有程序集查找:

var tableType = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(asm => asm.GetTypes())
    .FirstOrDefault(t => t.Name == item.TableName);

注意:这种方法性能稍差,频繁调用时建议缓存结果。

修正后的完整代码示例

var TemplateGroupList = _templateGTRRepository
    .GetAll()
    .Where(x => x.TemplateGroupId == template.Id)
    .ToList();

var PropertyList = new List<string>();
// 假设实体类统一在该命名空间下
const string entityNamespace = "YourApp.Entities";

foreach (var item in TemplateGroupList)
{
    // 拼接完整类型名
    string fullTypeName = $"{entityNamespace}.{item.TableName}";
    var tableType = Type.GetType(fullTypeName);

    if (tableType != null)
    { 
        var properties = tableType.GetProperties()
                                 .Select(t => t.Name)
                                 .ToList();
        foreach (var propertyName in properties)
        {
            PropertyList.Add($"{item.TableName}.{propertyName}");
        }
    }
}

额外检查项

  • 确认item.TableName的值和实际类名完全一致,包括大小写(比如User和user是不同名称)
  • 确认目标类是public修饰的,非public类型无法通过Type.GetType直接获取

内容的提问来源于stack exchange,提问作者Sanjay Kumar Mahato

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 09:20:10