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

如何通过字符串类名在不实例化的情况下读取类属性?

不实例化、不硬编码类名,通过字符串获取类属性的解决方法

你遇到的NullReferenceException,本质是Type.GetType(className)返回了null——Type.GetType默认只在当前执行程序集或系统核心程序集(如mscorlib)中查找类型,仅传入命名空间+类名的格式,大概率找不到目标类型。以下是无需实例化、无需硬编码类名的解决方案:

方案1:使用程序集限定名

如果知道类所在的程序集名称,直接把类名改成程序集限定名,格式为"命名空间.类名, 程序集名称"(注意程序集名称不要加.dll后缀)。

示例代码:

string className = "myNamespace.myClass, MyAssembly"; // 替换为你的程序集名称
PropertyInfo[] myPropertyInfo;
try
{
    Type targetType = Type.GetType(className);
    if (targetType != null)
    {
        myPropertyInfo = targetType.GetProperties();
        // 遍历输出属性信息示例
        foreach (var prop in myPropertyInfo)
        {
            Console.WriteLine($"{prop.Name} - {prop.PropertyType.Name}");
        }
    }
    else
    {
        Console.WriteLine("未找到目标类型");
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}

方案2:遍历已加载程序集查找类型

如果不清楚程序集名称,可以遍历当前AppDomain中已加载的所有程序集,逐个匹配目标类型:

示例代码:

string className = "myNamespace.myClass";
PropertyInfo[] myPropertyInfo = null;

// 遍历所有已加载的程序集
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
    Type targetType = assembly.GetType(className);
    if (targetType != null)
    {
        myPropertyInfo = targetType.GetProperties();
        break; // 找到后终止遍历
    }
}

if (myPropertyInfo != null)
{
    foreach (var prop in myPropertyInfo)
    {
        Console.WriteLine($"{prop.Name} - {prop.PropertyType.Name}");
    }
}
else
{
    Console.WriteLine("未找到目标类型");
}

补充:获取非公共属性

如果目标类包含private/protected/internal等非公共属性,需要给GetProperties传入BindingFlags参数指定查找范围:

// 同时获取公共和非公共的实例属性
myPropertyInfo = targetType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

以上两种方案都不需要实例化类对象,也无需硬编码类名,完全通过字符串变量实现类型查找与属性获取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 16:01:47