【发布时间】:2010-11-24 03:59:19
【问题描述】:
如果我有这个:
Type t = typeof(Dictionary<String, String>);
如何将"System.Collections.Generic.Dictionary" 作为字符串?是最好/唯一的方法吗:
String n = t.FullName.Substring(0, t.FullName.IndexOf("`"));
不过对我来说似乎有点骇人听闻。
我想要这个的原因是我想获取一个Type 对象,并生成类似于在 C# 源代码文件中找到的代码。我正在生成一些文本模板,我需要将类型作为字符串添加到源中,FullName 属性会生成如下内容:
System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089]]
而不是我想要的:
System.Collections.Generic.Dictionary<System.String, System.String>
编辑:好的,这是最终代码,对我来说仍然有点像 hack,但它确实有效:
/// <summary>
/// This method takes a type and produces a proper full type name for it, expanding generics properly.
/// </summary>
/// <param name="type">
/// The type to produce the full type name for.
/// </param>
/// <returns>
/// The type name for <paramref name="type"/> as a string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="type"/> is <c>null</c>.</para>
/// </exception>
public static String TypeToString(Type type)
{
#region Parameter Validation
if (Object.ReferenceEquals(null, type))
throw new ArgumentNullException("type");
#endregion
if (type.IsGenericType)
{
if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
Type underlyingType = type.GetGenericArguments()[0];
return String.Format("{0}?", TypeToString(underlyingType));
}
String baseName = type.FullName.Substring(0, type.FullName.IndexOf("`"));
return baseName + "<" + String.Join(", ", (from paramType in type.GetGenericArguments()
select TypeToString(paramType)).ToArray()) + ">";
}
else
{
return type.FullName;
}
}
【问题讨论】:
标签: c# .net reflection types