给定System.Type,为类定义生成源代码?

gre*_*mac 0 .net c# reflection

在.NET中有没有办法在给定System.Type的情况下创建源代码类定义?

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


string myTypeSourceCode = GetSourceCode( typeof(MyType) );
Run Code Online (Sandbox Code Playgroud)

基本上我在寻找GetSourceCode()是什么.

我意识到会有限制:如果有属性getter/setter或私有成员,则不包含源,但我不需要.假设类型是数据传输对象,因此只需公开公共属性/字段.

我正在使用它的是自动生成的Web API代码示例.

por*_*ges 5

如果您只想生成如您所示的伪接口代码,则可以迭代公共字段和属性,如下所示:

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();
} 
Run Code Online (Sandbox Code Playgroud)

对于类型:

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 {} }
}
Run Code Online (Sandbox Code Playgroud)

输出是:

public class MyType
{
   public Int32 test;
   public String Name { get; set; }
   public Int32 Age { get; set; }
   public Int32 ReadOnly { get; }
   public Int32 SetOnly { set; }
}
Run Code Online (Sandbox Code Playgroud)