C# 为给定System.Type的类定义生成源代码?

C# 为给定System.Type的类定义生成源代码?,c#,.net,reflection,C#,.net,Reflection,在.NET中有没有一种方法可以在给定System.Type的情况下创建源代码类定义 public class MyType { public string Name { get; set; } public int Age { get; set; } } string myTypeSourceCode = GetSourceCode( typeof(MyType) ); 基本上,我在寻找什么是GetSourceCode() 我意识到会有一些限制:如果有属性getter/sett

在.NET中有没有一种方法可以在给定System.Type的情况下创建源代码类定义

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


string myTypeSourceCode = GetSourceCode( typeof(MyType) );
基本上,我在寻找什么是GetSourceCode()

我意识到会有一些限制:如果有属性getter/setter或private成员,则不包括源代码,但我不需要这些。假设该类型是数据传输对象,那么只需要公开公共属性/字段

我使用它的目的是为web API自动生成代码示例。

试试.Net反编译器

以下是指向.net反编译器的一些链接





或者,当.Net Reflector免费时,您可能会找到它的旧版本…

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

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

您可以通过使用像ILSpy这样的现有反编译器来回避这个问题,但是枚举所有属性、检查是否有getter/setter并打印它们的类型也不难。