我如何获得通用类型的正确名称?
例如:此代码
typeof(List<string>).Name
Run Code Online (Sandbox Code Playgroud)
返回
List`1
代替
List<string>
Run Code Online (Sandbox Code Playgroud)
typeof(List<string>).ToString()
Run Code Online (Sandbox Code Playgroud)
返回System.Collections.Generic.List`1 [System.String]但我想得到初始名称:
List<string>
Run Code Online (Sandbox Code Playgroud)
这是真的吗?
Ada*_*lls 35
使用FullName属性.
typeof(List<string>).FullName
Run Code Online (Sandbox Code Playgroud)
这将为您提供名称空间+类+类型参数.
您要求的是C#特定语法.就.NET而言,这是正确的:
System.Collections.Generic.List`1[System.String]
Run Code Online (Sandbox Code Playgroud)
因此,为了得到你想要的东西,你必须编写一个函数来按照你想要的方式构建它.也许是这样的:
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;
}
Run Code Online (Sandbox Code Playgroud)
对于这些类型(true为第2个参数):
typeof( List<string> ) )
typeof( List<Dictionary<int, string>> )
Run Code Online (Sandbox Code Playgroud)
它返回:
List<String>
List<Dictionary<Int32, String>>
Run Code Online (Sandbox Code Playgroud)
一般来说,我敢打赌,你可能不需要拥有代码的C#表示,也许如果你这样做,一些比C#语法更好的格式会更合适.
你可以用这个:
public static string GetTypeName(Type t) {
if (!t.IsGenericType) return t.Name;
if (t.IsNested && t.DeclaringType.IsGenericType) throw new NotImplementedException();
string txt = t.Name.Substring(0, t.Name.IndexOf('`')) + "<";
int cnt = 0;
foreach (Type arg in t.GetGenericArguments()) {
if (cnt > 0) txt += ", ";
txt += GetTypeName(arg);
cnt++;
}
return txt + ">";
}
Run Code Online (Sandbox Code Playgroud)
例如:
static void Main(string[] args) {
var obj = new Dictionary<string, Dictionary<HashSet<int>, int>>();
string s = GetTypeName(obj.GetType());
Console.WriteLine(s);
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
输出:
Dictionary<String, Dictionary<HashSet<Int32>, Int32>>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28299 次 |
| 最近记录: |