c# - 获取类型名称

标签 c# generics

我如何获得泛型的完整正确名称?

例如: 这段代码

typeof(List<string>).Name

返回

List`1

代替

List<string>

如何起个好名字?

typeof(List<string>).ToString()

返回 System.Collections.Generic.List`1[System.String] 但我想获取初始名称:

List<string>

这是真的吗?

最佳答案

使用 FullName property .

typeof(List<string>).FullName

这将为您提供命名空间 + 类 + 类型参数。

您要求的是特定于 C# 的语法。就 .NET 而言,这是正确的:

System.Collections.Generic.List`1[System.String]

因此,要获得您想要的内容,您必须编写一个函数来按照您想要的方式构建它。或许是这样的:

static string GetCSharpRepresentation( Type t, bool trimArgCount ) {
    if( t.IsGenericType ) {
        var genericArgs = t.GetGenericArguments().ToList();

        return GetCSharpRepresentation( t, trimArgCount, genericArgs );
    }

    return t.Name;
}

static string GetCSharpRepresentation( Type t, bool trimArgCount, List<Type> availableArguments ) {
    if( t.IsGenericType ) {
        string value = t.Name;
        if( trimArgCount && value.IndexOf("`") > -1 ) {
            value = value.Substring( 0, value.IndexOf( "`" ) );
        }

        if( t.DeclaringType != null ) {
            // This is a nested type, build the nesting type first
            value = GetCSharpRepresentation( t.DeclaringType, trimArgCount, availableArguments ) + "+" + value;
        }

        // Build the type arguments (if any)
        string argString = "";
        var thisTypeArgs = t.GetGenericArguments();
        for( int i = 0; i < thisTypeArgs.Length && availableArguments.Count > 0; i++ ) {
            if( i != 0 ) argString += ", ";

            argString += GetCSharpRepresentation( availableArguments[0], trimArgCount );
            availableArguments.RemoveAt( 0 );
        }

        // If there are type arguments, add them with < >
        if( argString.Length > 0 ) {
            value += "<" + argString + ">";
        }

        return value;
    }

    return t.Name;
}

对于这些类型(第二个参数为 true):

typeof( List<string> ) )
typeof( List<Dictionary<int, string>> )

它返回:

List<String>
List<Dictionary<Int32, String>>

但总的来说,我敢打赌您可能需要拥有代码的 C# 表示,也许如果您需要,一些比 C# 语法更好的格式会更合适。

关于c# - 获取类型名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2579734/

相关文章:

java - RESTful 服务返回 String[] 对象时出现问题

java - 设计模式 : Lazy Singleton, 泛型和继承 : java. lang.Class 无法转换为 java.lang.reflect.ParameterizedType

c# - 从哈希表中读取匹配的记录到类对象中

Java,不同对象的重复逻辑 block ,清理代码

java - 为什么 void method1(T obj) 不允许泛型?

c# - 有没有办法将通过 TaskCompletionSource 驱动的任务设置为 Status 'Running' ?

c# - 如何在不在 csproj 中链接到项目的情况下引用项目?

c# - 在互操作方法中为 `null` 参数传递 `ref struct` 引用

c# - SimpleInjector结合了WCF和“常规”注册

c# - 如何将弯曲的文本渲染成位图?