以编程方式生成C#代码文件的干净,高效,绝对可靠的方法

Max*_*Max 2 .net c# code-generation

我想知道是否有任何好方法以编程方式生成C#代码而不实际操作字符串或StringBuilders.此外,它应检查代码是否编译,但我想这可以使用CSharpCodeProvider完成.

我正在寻找以下内容:

CodeUnit unit = new CodeUnit();
unit.AddDefaultUsings();
unit.AddUsing("MyApi.CoolNameSpace", "MyApi.Yay");
var clazz = unit.AddClass("GeneratedClass", Access.Public);
clazz.AddConstructor("....");
if(unit.Compile() != true)
    //oh dang, somethings wrong!
else unit.WriteUTF8To("GeneratedClass.cs");
Run Code Online (Sandbox Code Playgroud)

这可能是核心库的一部分(不要认为CSharpCodeProvider可以做到这一点?)或外部库,但这根本不是我的强项(使用c#动态生成代码),所以如果这看起来毫无头绪,那是因为我!

svi*_*ick 5

这正是CodeDOM的用途:

var unit = new CodeCompileUnit();

var @namespace = new CodeNamespace("GeneratedCode");
unit.Namespaces.Add(@namespace);

// AddDefault() doesn't exist, but you can create it as an extension method
@namespace.Imports.AddDefault();
@namespace.Imports.Add(new CodeNamespaceImport("MyApi.CoolNameSpace"));

var @class = new CodeTypeDeclaration("GeneratedClass");
@namespace.Types.Add(@class);

@class.TypeAttributes = TypeAttributes.Class | TypeAttributes.Public;

var constructor = new CodeConstructor();
constructor.Attributes = MemberAttributes.Public;
constructor.Parameters.Add(
    new CodeParameterDeclarationExpression(typeof(string), "name"));

constructor.Statements.Add(…);

@class.Members.Add(constructor);

var provider = new CSharpCodeProvider();

var result = provider.CompileAssemblyFromDom(new CompilerParameters(), unit);
Run Code Online (Sandbox Code Playgroud)

虽然它可能非常冗长.此外,它尝试与语言无关,这意味着您无法使用此API的静态类,扩展方法,LINQ查询表达式或lambda等C#特定功能.你可以做的是将任何字符串放在方法体内.使用此功能,您可以使用某些特定于C#的功能,但只能使用您尝试避免的字符串操作.