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

C#中如何通过传入的Type参数访问对应类的静态字段

错误原因

type is Core core触发编译错误的核心原因是:入参type是System.Type类型的反射对象,和你自定义的Core业务类不存在继承关系,无法直接通过模式匹配转换为Core实例。
另外你当前代码里的Info是定义在Core上的实例抽象属性,根本不是静态字段,访问实例属性必须先持有对应类的实例,不存在直接通过Type对象拿实例属性值的可能。

可行实现方案

方案1:保留传入Type的调用方式,通过反射创建实例取值

不需要修改现有业务类和调用方代码,仅调整Button方法逻辑即可:

using System;

private static bool Button(Type type)
{
    // 校验传入类型是否为Core的子类
    if (!typeof(Core).IsAssignableFrom(type))
    {
        Debug.LogError($"传入类型[{type.Name}]未继承Core基类");
        return false;
    }

    // 通过反射创建无参实例
    Core coreInstance = Activator.CreateInstance(type) as Core;
    if (coreInstance == null) return false;
    
    Debug.Log(coreInstance.Info);
    return true;
}

注意:该方案要求所有Core子类都提供公开无参构造函数,否则Activator.CreateInstance会抛出运行时异常。

方案2:改用泛型方法,编译期类型检查无反射开销

如果可以调整Button方法签名,优先选这个方案,性能更好且不会出现运行时类型错误:

// 泛型约束:T必须是Core子类,且包含无参构造
private static bool Button<T>() where T : Core, new()
{
    T coreInstance = new T();
    Debug.Log(coreInstance.Info);
    return true;
}

对应调用方代码修改为:

public class SomeClass
{
    private void MainStart()
    {
        Panel.Button<CoreB>(); // 直接输出 "Core B Info"
    }
}

补充:如果后续确实需要访问类的静态成员

如果你把Info改为各子类的静态属性/字段,不需要创建实例,直接通过反射获取静态值即可:

using System.Reflection;

private static bool Button(Type type)
{
    if (!typeof(Core).IsAssignableFrom(type))
    {
        Debug.LogError($"传入类型[{type.Name}]未继承Core基类");
        return false;
    }

    // 查找公共静态属性Info
    PropertyInfo staticInfoProp = type.GetProperty("Info", BindingFlags.Public | BindingFlags.Static);
    if (staticInfoProp == null) return false;

    string infoValue = staticInfoProp.GetValue(null) as string;
    Debug.Log(infoValue);
    return true;
}

静态成员属于类本身,不属于类的实例,访问时不需要传实例对象,GetValue方法第一个参数传null即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 06:15:48