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

如何在Godot C#中通过反射向泛型Queue添加对象?

解决方案:编译时未知泛型类型下向Queue添加元素

你的核心问题在于泛型类型的不变性以及反射获取方法时未匹配实际泛型队列类型,以下是具体解决方法:

错误原因分析

  1. 无法强制转换Queue到Queue:Queue<T>是不变泛型类型,即便Expense继承自object,也不能将Queue<Expense>直接转为Queue<object>,这是C#泛型的类型安全限制。
  2. 反射获取Enqueue方法错误:你用typeof(Queue).GetMethod("Enqueue")获取的是非泛型Queue的方法,而实际目标对象是泛型Queue<Expense>,类型不匹配导致TargetException;用Queue<object>同样存在类型不匹配问题。
  3. 正确实现代码

    修改读档中处理Queue的逻辑,通过反射获取实际泛型队列类型的Enqueue方法并调用:

    if (propertyInfo.PropertyType.IsGenericType && 
        propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Queue<>))
    {
        Type genericArgument = propertyInfo.PropertyType.GetGenericArguments()[0];
        Variant variant = Json.ParseString(stringVal);
        Godot.Collections.Dictionary<string, Variant> queueDict = (Godot.Collections.Dictionary<string, Variant>)variant;
    
        // 获取目标队列实例
        object queueInstance = propertyInfo.GetValue(newObject);
        // 获取该泛型Queue<T>对应的Enqueue方法
        MethodInfo enqueueMethod = propertyInfo.PropertyType.GetMethod("Enqueue", new[] { genericArgument });
    
        foreach (KeyValuePair<string, Variant> pair in queueDict)
        {
            string queueElementString = (string)pair.Value;
            object queueObject = CreateDefaultObject(queueElementString);
            
            // 反射调用Enqueue方法完成元素入队
            enqueueMethod.Invoke(queueInstance, new[] { queueObject });
        }
        return true;
    }
    

    关键步骤说明

    1. 获取实际队列实例:直接从newObject的属性中拿到已初始化的Queue<Expense>实例。
    2. 匹配正确的Enqueue方法:通过propertyInfo.PropertyType(即Queue<Expense>类型)获取对应的Enqueue方法,确保方法参数类型与queueObject一致。
    3. 反射调用入队:传入队列实例和待添加元素,完成入队操作。

    扩展:通用集合处理优化

    如果后续需要支持List<T>等其他泛型集合,可将集合处理逻辑抽象为通用方法,核心思路一致:

    • 判断集合类型的泛型定义(如typeof(List<>))
    • 获取对应集合的添加方法(如Add)
    • 反射调用添加方法完成元素填充

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 01:55:19