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

如何查找可分配给IService<int>的开放泛型闭包类及非泛型实现类?

解决方案

要实现这个需求,我们可以利用.NET反射API,分两类情况筛选程序集中的类型:直接实现IService<int>的非泛型类,以及泛型参数数量为1的开放泛型类闭包为Service<int>后符合条件的类型。

核心思路

  1. 确定目标封闭接口类型:typeof(IService<int>)
  2. 遍历目标程序集中的所有类型,对每个类型做以下判断:
    • 非泛型类型:直接检查是否可分配给目标接口
    • 开放泛型类型:仅保留泛型参数数量为1的类,将其闭包为对应参数的封闭类型后,检查是否可分配给目标接口
  3. 排除接口本身和抽象类(如果不需要实例化可去掉抽象类判断)

代码实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

public interface IService<T> { }
public class Service<T> : IService<T> { }
public class SpecialService : IService<int> { }
public class EdgeCaseService<T, U> : IService<T> { } // 会被排除的类型

class Program
{
    static void Main()
    {
        Type targetInterface = typeof(IService<int>);
        Assembly assembly = Assembly.GetExecutingAssembly(); // 替换为你要扫描的目标程序集

        List<Type> matchingTypes = new List<Type>();

        foreach (Type type in assembly.GetTypes())
        {
            // 排除接口和抽象类
            if (type.IsInterface || type.IsAbstract)
                continue;

            // 处理非泛型类型
            if (!type.IsGenericType)
            {
                if (targetInterface.IsAssignableFrom(type))
                {
                    matchingTypes.Add(type);
                }
                continue;
            }

            // 处理开放泛型类型,仅保留泛型参数数量为1的类
            if (type.IsGenericTypeDefinition && type.GetGenericArguments().Length == 1)
            {
                // 闭包泛型类为目标参数类型
                Type closedGenericType = type.MakeGenericType(typeof(int));
                if (targetInterface.IsAssignableFrom(closedGenericType))
                {
                    matchingTypes.Add(closedGenericType);
                }
            }
        }

        // 输出匹配结果
        foreach (Type type in matchingTypes)
        {
            Console.WriteLine(type.FullName);
        }
    }
}

代码说明

  • type.IsGenericTypeDefinition:判断当前类型是否为开放泛型类(比如Service<T>而非已指定参数的Service<int>)
  • MakeGenericType(typeof(int)):将开放泛型类转换为使用int作为泛型参数的封闭类型
  • IsAssignableFrom:验证类型是否具备继承/实现目标接口的关系,确保可分配性

运行代码后,输出结果会包含SpecialService和Service<int>,而EdgeCaseService<T,U>因泛型参数数量不符会被自动过滤。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 16:43:21