简体   繁体   中英

Generate source code for class definition given a System.Type?

Is there a way in .NET to create the source code class definition given a System.Type?

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


string myTypeSourceCode = GetSourceCode( typeof(MyType) );

Basically I'm looking for what GetSourceCode() is.

I realize there would be limitations: If there are property getters/setters or private members the source is not included, but I don't need that. Assume the type is a Data Transfer Object, so just the public properties/fields need to be exposed.

What I'm using this for is auto-generated code examples for a web API.

If you just want to generate pseudo-interface code like you have shown, you can iterate over the public fields & properties like this:

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();
} 

For the type:

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 {} }
}

The output is:

public class MyType
{
   public Int32 test;
   public String Name { get; set; }
   public Int32 Age { get; set; }
   public Int32 ReadOnly { get; }
   public Int32 SetOnly { set; }
}

Try a .Net decompiler

Here are some links to .net decompiler
http://www.telerik.com/products/decompiler.aspx
http://www.jetbrains.com/decompiler/
http://www.devextras.com/decompiler/
http://wiki.sharpdevelop.net/ilspy.ashx
or maybe you'll be able to find an old version of .Net Reflector when it was free...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM