创建一个类用CodeTypeDeclaration cTDeclaration = new CodeTypeDeclaration("类名");
这样创建出的是非静态类。我想创建一个static类,试了一下cTDeclaration.TypeAttributes属性值,好像找不到对应的枚举值表示静态类的。
请问如何创建静态类?我想用CodeDom创建并得到该静态类的源代码。谢谢。
可以试试 stackoverflow 上 Creating extension method using CodeDOM 回答中的变通方法,我试验的代码如下:
using Microsoft.CSharp;
using System.CodeDom;
using System.CodeDom.Compiler;
var staticClass = new CodeTypeDeclaration("Answer");
staticClass.StartDirectives.Add(new CodeRegionDirective(
CodeRegionMode.Start, Environment.NewLine + "\tstatic"));
staticClass.EndDirectives.Add(new CodeRegionDirective(
CodeRegionMode.End, string.Empty));
var codeProvider = new CSharpCodeProvider();
var compileUnit = new CodeCompileUnit();
var nameSpace = new CodeNamespace("Cnblogs");
compileUnit.Namespaces.Add(nameSpace);
nameSpace.Types.Add(staticClass);
using var writer = new StringWriter();
codeProvider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions());
var code = writer.ToString();
Console.WriteLine(code);
注:上面的代码还参考了 https://stackoverflow.com/a/411001/5989202
控制台输出结果:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Cnblogs {
#region
static
public class Answer {
}
#endregion
}
强啊 大佬