泛型接口类型

本文关键字:接口类型 泛型 | 更新日期: 2023-09-27 18:18:23

我做了一个小项目,从我导入的dll中得到反射的所有接口,继承了我的" ibbase "接口,像这样

 Type[] services = typeof(DataAccess.IXXX).Assembly.GetTypes();
 foreach (Type SC in services)
        {
            if (SC.IsInterface)
            {
                if (SC.GetInterfaces().Contains(typeof(DataAccess.IBase)))
                {
                    file.WriteLine(SC.Name);
                }
             }
         }

问题是我的很多接口包含泛型

public interface IExample<TKey, Tvalue, TCount> : IBase

但是我的SC.Name是这样写的

IExample'3

你能帮我吗?

泛型接口类型

IExample'3是具有3个泛型类型参数的接口的内部名称(您可能已经猜到了)。要获取类或接口的泛型类型参数,请使用Type.GetGenericArguments

您可以使用如下命令打印正确的名称

var type = typeof(IExample<int, double>);
var arguments = Type.GetGenericArguments(type);
if(arguments.Any())
{
    var name = argument.Name.Replace("'" + arguments.Length, "");
    Console.Write(name + "<");
    Console.Write(string.Join(", ", arguments.Select(x => x.Name));     
    Console.WriteLine(">")
}
else
{
    Console.WriteLine(type.Name);
}

我想是Type。GetGenericArguments方法是你需要的

可以看到,. net name属性并没有将泛型参数类型作为名称的一部分显示给您。你必须从GetGenericArguments中获取参数类型。

这是一个返回c#风格的泛型类型名称的方法。它是递归的,所以它可以处理具有泛型类型作为参数的泛型,即IEnumerable<IDictionary<string, int>>

using System.Collections.Generic;
using System.Linq;
static string FancyTypeName(Type type)
{
    var typeName = type.Name.Split('`')[0];
    if (type.IsGenericType)
    {
        typeName += string.Format("<{0}>", string.Join(",", type.GetGenericArguments().Select(v => FancyTypeName(v)).ToArray()));
    }
    return typeName;
}