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

如何实现字典中指定子类型StructureData的泛型查询方法?

解决方案

首先,你的原始GetRoadDataWithin方法存在一个问题:它返回的是IEnumerable<List<StructureData>>却强制转换为IEnumerable<RoadStructureData>,这会导致运行时类型转换错误。正确的做法应该是使用SelectMany来展平所有列表中的元素,而不是直接选择列表本身。

针对你的需求,有两种可行的实现方式:


1. 使用泛型方法(推荐,类型安全)

这种方式利用泛型参数指定目标类型,既能获得编译时类型检查,又能简化代码:

public IEnumerable<T> GetDataWithinOfType<T>(IntBound position) where T : StructureData
{
    return structuresDataCollection
        .Where(s => s.Key.Intersects(position))
        .SelectMany(s => s.Value.OfType<T>());
}

使用示例:

var roadData = GetDataWithinOfType<RoadStructureData>(somePosition);

2. 使用Type参数(适用于类型仅在运行时确定的场景)

如果必须通过Type变量指定类型,可以手动检查每个元素的类型来替代OfType<T>:

public IEnumerable<StructureData> GetDataWithinOfType(IntBound position, Type requiredType)
{
    if (requiredType == null || !typeof(StructureData).IsAssignableFrom(requiredType))
        throw new ArgumentException("requiredType必须是StructureData的子类或自身", nameof(requiredType));

    return structuresDataCollection
        .Where(s => s.Key.Intersects(position))
        .SelectMany(s => s.Value.Where(item => requiredType.IsAssignableFrom(item.GetType())));
}

使用示例:

var roadData = GetDataWithinOfType(somePosition, typeof(RoadStructureData));

关键说明:

  • SelectMany用于将多个List<StructureData>展平为单个元素序列,这是修复原始方法错误的核心步骤。
  • IsAssignableFrom方法可以正确处理继承关系,确保匹配目标类型及其子类(如果需要严格匹配类型,可以改用item.GetType() == requiredType)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 21:42:39