2010-03-06 19 views
3

我需要一個會類型轉換爲字符串的函數,例如:如何將類型轉換爲可以在vb .net中編譯的字符串?

Dim foo as Dictionary(of Dictionary(of Integer, String), Integer) 
Debug.WriteLine(TypeToString(GetType(foo))) 

在調試輸出,我希望看到的東西等同於:

Dictionary(of Dictionary(of Integer, String), Integer) 

回答

2

這裏的一些推廣方法我用你問什麼,但它在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; 
} 
+1

命名變量'return'和'this'是一個可怕的想法。 – 2010-03-06 09:23:12

+0

我認爲這是神話般的。非常清楚擴展方法擴展了什麼變量,我可以清楚地看到我返回的值。 「@」有助於突出這兩個重要變量。達林,你能告訴我爲什麼你認爲這是一個可怕的想法? – Enigmativity 2010-03-06 09:28:27

+0

我想我在@Darin這裏同意。 「this」和「return」這兩個詞具有非常明確的含義和用法。即使你(必要時)以'@'爲前綴變量,我仍然覺得比澄清更令人困惑。而不是'@ return',我會親自命名變量'result'。 'return result;'似乎比'return @return'更明顯;'@ this'的情況下,它可以簡單地命名爲'type'或'typeSequence',我認爲這更有助於澄清它代表什麼。 – 2010-03-06 09:53:17

0

是不是foo.GetType().ToString()可以接受嗎?在這個例子情況下,它會返回

System.Collections.Generic.Dictionary`2[System.Collections.Generic.Dictionary`2[System.Int32,System.String],System.Int32] 
+0

我無法編譯。 – Eyal 2010-03-06 12:46:30

相關問題