简体   繁体   English

c# - 通用接口类型

[英]c# - Generic interfaces types

i've made a mini project to get with reflection all the interfaces from the dll i've imported, that inherits from my "IBase" interface like this 我做了一个迷你项目来反映我导入的dll的所有接口,这些接口继承自我的“IBase”界面

 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);
                }
             }
         }

The problem is that a lot of my interfaces contains generics 问题是我的很多接口都包含泛型

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

But my SC.Name write that like this 但是我的SC.Name就是这样写的

IExample'3

Can you help me ? 你能帮助我吗 ?

IExample'3 is the internal name of the of an interface with 3 generic type arguments (as you have probably already guessed). IExample'3是具有3个泛型类型参数的接口的内部名称(正如您可能已经猜到的那样)。 To get the generic type arguments of a class or interface use the Type.GetGenericArguments 要获取类或接口的泛型类型参数,请使用Type.GetGenericArguments

You can use something like this to print the correct name 您可以使用类似的东西来打印正确的名称

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方法就是你所需要的

As you can see, the .NET name property doesn't show you the generic parameter types as part of the name. 如您所见,.NET name属性不会将通用参数类型显示为名称的一部分。 You have to get the parameter types from GetGenericArguments. 您必须从GetGenericArguments获取参数类型。

Here is a method returns the name of a generic type in the C# style. 这是一个方法返回C#样式中泛型类型的名称。 It is recursive, so it can handle generics that have generic types as parameters ie IEnumerable<IDictionary<string, int>> 它是递归的,因此它可以处理具有泛型类型作为参数的泛型,即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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM