2012-02-01 56 views
0

在.NET中有沒有一種方法可以創建給定System.Type的源代碼類定義?給定一個System.Type生成類定義的源代碼?

public class MyType 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
} 


string myTypeSourceCode = GetSourceCode(typeof(MyType)); 

基本上我在找什麼GetSourceCode()。

我意識到會有侷限性:如果有屬性獲取者/設置者或私有成員,則不包括源,但我不需要這樣做。假設類型是數據傳輸對象,那麼只需公開屬性/域就可以了。

我使用的是自動生成的Web API代碼示例。

+0

您可以通過使用側步的問題,現有的像ILSpy這樣的反編譯器。 – CodesInChaos 2012-02-01 22:59:15

+1

但列舉所有屬性,檢查是否有一個getter/setter和打印他們的類型也不應該很難。 – CodesInChaos 2012-02-01 23:00:05

回答

5

如果你只是想生成像你所示的僞接口代碼,你c

string GetSourceCode(Type t) 
{ 
    var sb = new StringBuilder(); 
    sb.AppendFormat("public class {0}\n{{\n", t.Name); 

    foreach (var field in t.GetFields()) 
    { 
     sb.AppendFormat(" public {0} {1};\n", 
      field.FieldType.Name, 
      field.Name); 
    } 

    foreach (var prop in t.GetProperties()) 
    { 
     sb.AppendFormat(" public {0} {1} {{{2}{3}}}\n", 
      prop.PropertyType.Name, 
      prop.Name, 
      prop.CanRead ? " get;" : "", 
      prop.CanWrite ? " set; " : " "); 
    } 

    sb.AppendLine("}"); 
    return sb.ToString(); 
} 

對於類型:

public class MyType 
{ 
    public int test; 
    public string Name { get; set; } 
    public int Age { get; set; } 
    public int ReadOnly { get { return 1; } } 
    public int SetOnly { set {} } 
} 

輸出是:在公共領域&這類似一個迭代

public class MyType 
{ 
    public Int32 test; 
    public String Name { get; set; } 
    public Int32 Age { get; set; } 
    public Int32 ReadOnly { get; } 
    public Int32 SetOnly { set; } 
} 
相關問題