Genere código fuente para la definición de clase dado un 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.

preguntado el 01 de febrero de 12 a las 22:02

You could side-step the problem by using an existing decompiler like ILSpy. -

But enumerating all properties, checking if the have a getter/setter and printing their type shouldn't be hard either. -

2 Respuestas

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

El resultado es:

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

Respondido 02 Feb 12, 03:02

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...

Respondido 02 Feb 12, 03:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.