簡體   English   中英

c# - 通用接口類型

[英]c# - Generic interfaces types

我做了一個迷你項目來反映我導入的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);
                }
             }
         }

問題是我的很多接口都包含泛型

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM