我如何获得泛型的完整正确名称?
例如: 这段代码
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/