我需要一个会类型转换为字符串的函数,例如:如何将类型转换为可以在vb .net中编译的字符串?
Dim foo as Dictionary(of Dictionary(of Integer, String), Integer)
Debug.WriteLine(TypeToString(GetType(foo)))
在调试输出,我希望看到的东西等同于:
Dictionary(of Dictionary(of Integer, String), Integer)
我需要一个会类型转换为字符串的函数,例如:如何将类型转换为可以在vb .net中编译的字符串?
Dim foo as Dictionary(of Dictionary(of Integer, String), Integer)
Debug.WriteLine(TypeToString(GetType(foo)))
在调试输出,我希望看到的东西等同于:
Dictionary(of Dictionary(of Integer, String), Integer)
这里的一些推广方法我用你问什么,但它在C#和生成C#。
您可以保留它在C#中,但将输出更改为VB.Net或完全转换为VB.Net,如果你喜欢。
public static string ToCode(this Type @this)
{
string @return = @this.FullName ?? @this.Name;
Type nt = Nullable.GetUnderlyingType(@this);
if (nt != null)
{
return string.Format("{0}?", nt.ToCode());
}
if (@this.IsGenericType & [email protected])
{
Type gtd = @this.GetGenericTypeDefinition();
return string.Format("{0}<{1}>", gtd.ToCode(), @this.GetGenericArguments().ToCode());
}
if (@return.EndsWith("&"))
{
return Type.GetType(@this.AssemblyQualifiedName.Replace("&", "")).ToCode();
}
if (@this.IsGenericTypeDefinition)
{
@return = @return.Substring(0, @return.IndexOf("`"));
}
switch (@return)
{
case "System.Void":
@return = "void";
break;
case "System.Int32":
@return = "int";
break;
case "System.String":
@return = "string";
break;
case "System.Object":
@return = "object";
break;
case "System.Double":
@return = "double";
break;
case "System.Int64":
@return = "long";
break;
case "System.Decimal":
@return = "decimal";
break;
case "System.Boolean":
@return = "bool";
break;
}
return @return;
}
public static string ToCode(this IEnumerable<Type> @this)
{
var @return = "";
var ts = @this.ToArray<Type>();
if (ts.Length > 0)
{
@return = ts[0].ToCode();
if (ts.Length > 1)
{
foreach (Type t in ts.Skip<Type>(1))
{
@return = @return + string.Format(", {0}", t.ToCode());
}
}
}
return @return;
}
是不是foo.GetType().ToString()
可以接受吗?在这个例子情况下,它会返回
System.Collections.Generic.Dictionary`2[System.Collections.Generic.Dictionary`2[System.Int32,System.String],System.Int32]
我无法编译。 – Eyal 2010-03-06 12:46:30
命名变量'return'和'this'是一个可怕的想法。 – 2010-03-06 09:23:12
我认为这是神话般的。非常清楚扩展方法扩展了什么变量,我可以清楚地看到我返回的值。 “@”有助于突出这两个重要变量。达林,你能告诉我为什么你认为这是一个可怕的想法? – Enigmativity 2010-03-06 09:28:27
我想我在@Darin这里同意。 “this”和“return”这两个词具有非常明确的含义和用法。即使你(必要时)以'@'为前缀变量,我仍然觉得比澄清更令人困惑。而不是'@ return',我会亲自命名变量'result'。 'return result;'似乎比'return @return'更明显;'@ this'的情况下,它可以简单地命名为'type'或'typeSequence',我认为这更有助于澄清它代表什么。 – 2010-03-06 09:53:17