给定一个类型的实例,如何在C#中得到泛型类型的名字吗? [英] Given a type instance, how to get generic type name in C#?

查看:128
本文介绍了给定一个类型的实例,如何在C#中得到泛型类型的名字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个泛型类型,包括

Given a generic type, including

List<string>
Nullable<Int32>



我如何获得C#的通用名称?

how do i get a generic name for C#?

var t = typeof(Nullable<DateTime>);    
var s = t.GetGenericTypeDefinition().Name + "<" + t.GetGenericArguments()[0].Name + ">";

这收益率

"Nullable`1<DateTime>"



,但我需要

, but i need

"Nullable<DateTime>"



.

推荐答案

我看你已经接受一个答案,但说实话,这个问题的答案是不会有足够可靠地做到这一点,如果你只是结合什么在那里你已经写了。这是在正确的轨道上,但你的代码将只与一个泛型参数的泛型类型的工作,而当泛型类型参数本身不是泛型它只会工作!

I see you already accepted an answer, but honestly, that answer isn't going to be enough to do this reliably if you just combine what's in there with what you already wrote. It's on the right track, but your code will only work for generic types with exactly one generic parameter, and it will only work when the generic type parameter itself is not generic!

这是一个函数(写为扩展方法),应在所有情况下的实际工作:

This is a function (written as an extension method) that should actually work in all cases:

public static class TypeExtensions
{
    public static string ToGenericTypeString(this Type t)
    {
        if (!t.IsGenericType)
            return t.Name;
        string genericTypeName = t.GetGenericTypeDefinition().Name;
        genericTypeName = genericTypeName.Substring(0,
            genericTypeName.IndexOf('`'));
        string genericArgs = string.Join(",",
            t.GetGenericArguments()
                .Select(ta => ToGenericTypeString(ta)).ToArray());
        return genericTypeName + "<" + genericArgs + ">";
    }
}

这功能是递归的和安全的。如果在此输入运行它:

This function is recursive and safe. If you run it on this input:

Console.WriteLine(
    typeof(Dictionary<string, List<Func<string, bool>>>)
    .ToGenericTypeString());

您收到此(正确)的输出:

You get this (correct) output:

Dictionary<String,List<Func<String,Boolean>>>

这篇关于给定一个类型的实例,如何在C#中得到泛型类型的名字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆