gpt4 book ai didi

c# - 尝试使用 Codedom 生成代码时出错

转载 作者:行者123 更新时间:2023-11-30 22:37:12 25 4
gpt4 key购买 nike

我的目标:通过使用 CodeDom 创建一个 Windows 窗体应用程序(可执行)。我的意思是我想要一个表单(表单后面有一些代码)并将其转换为可执行文件(就像我进入 Visual Studio 并单击“构建”>“构建文件”一样)。诚然,我在网上找到了这个示例,并对其进行了轻微修改。我在尝试生成此代码时遇到错误 - 我以前从未见过的错误。此外,我在 Google 上找不到这些错误(很奇怪吧?)...

这是我得到的错误:不支持元素类型 System.CodeDom.CodeExpression。参数名称:e

我在以下行收到此错误:

CodeProvider.GenerateCodeFromCompileUnit(Unit, writer, new CodeGeneratorOptions());

这是我的完整代码:

{

CodeDomProvider CodeProvider = CodeDomProvider.CreateProvider("CSharp");

// Create the Unit
CodeCompileUnit Unit = new CodeCompileUnit();

// Define a namespace and add Imports statements
CodeNamespace Namespaces = new CodeNamespace("Test.CreateForm");
Namespaces.Imports.Add(new CodeNamespaceImport("System"));
Namespaces.Imports.Add(new CodeNamespaceImport("System.Drawing"));
Namespaces.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
Namespaces.Imports.Add(new CodeNamespaceImport("System.Xml"));
Namespaces.Imports.Add(new CodeNamespaceImport("System.Data"));

Unit.Namespaces.Add(Namespaces);

// Declare the type including base type
CodeTypeDeclaration MyType = new CodeTypeDeclaration("Form1");
MyType.IsClass = true;
MyType.TypeAttributes = System.Reflection.TypeAttributes.Public;
MyType.BaseTypes.Add("System.Windows.Forms.Form");

Namespaces.Types.Add(MyType);

// Create the constructor and add code
CodeConstructor Constructor = new CodeConstructor();

Constructor.Statements.Add(
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression(),"InitializeComponent", new CodeExpression() {}));

Constructor.Attributes = MemberAttributes.Public ;

MyType.Members.Add(Constructor);

// Declare component container
MyType.Members.Add(new CodeMemberField("System.ComponentModel.IContainer", "components"));



// Implement the Dispose method
CodeMemberMethod DisposeMethod = new CodeMemberMethod();

DisposeMethod.Name = "Dispose";
DisposeMethod.Attributes = MemberAttributes.Family;

DisposeMethod.Parameters.Add(
new CodeParameterDeclarationExpression(
typeof(Boolean), "disposing"));

CodeConditionStatement Statement = new CodeConditionStatement();
Statement.Condition = new CodeArgumentReferenceExpression("disposing");

CodeConditionStatement TrueStatement = new CodeConditionStatement();
TrueStatement.Condition =
new CodeBinaryOperatorExpression(
new CodeArgumentReferenceExpression("components"),
CodeBinaryOperatorType.IdentityInequality,
new CodePrimitiveExpression(null));

TrueStatement.TrueStatements.Add(
new CodeMethodInvokeExpression(
new CodeFieldReferenceExpression(null,
"components"), "Dispose", new CodeExpression() {}));

Statement.TrueStatements.Add(TrueStatement);

DisposeMethod.Statements.Add(Statement);

DisposeMethod.Statements.Add(new CodeMethodInvokeExpression( new CodeBaseReferenceExpression(), "Dispose", new CodeArgumentReferenceExpression[]
{new CodeArgumentReferenceExpression("disposing")}));

MyType.Members.Add(DisposeMethod);


// InitializeComponent
CodeMemberMethod InitializeMethod = new CodeMemberMethod();

InitializeMethod.Name = "InitializeComponent";
InitializeMethod.Attributes = MemberAttributes.Private;

InitializeMethod.CustomAttributes.Add(
new CodeAttributeDeclaration(
"System.Diagnostics.DebuggerStepThrough"));

InitializeMethod.Statements.Add(
new CodeAssignStatement(
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "components"),
new CodeObjectCreateExpression(
new CodeTypeReference(
typeof(System.ComponentModel.Container)),
new CodeExpression() { })));

MyType.Members.Add(InitializeMethod);

// Main entry point
CodeEntryPointMethod MainMethod = new CodeEntryPointMethod();
MainMethod.Name = "Main";
MyType.Members.Add(MainMethod);

//Add mouse move event
CodeMemberEvent eventstate = new CodeMemberEvent();
eventstate.Name = "MouseMove";
eventstate.Attributes = MemberAttributes.Final | MemberAttributes.Public;
eventstate.Type = new CodeTypeReference("System.Windows.Forms.MouseEventHandler");
MyType.Members.Add(eventstate);

string OutputName = "Some.cs";

try
{

CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BlankLinesBetweenMembers = true;
options.ElseOnClosing = false;
options.BracingStyle = "C";

// This is what we'll write the generated code to
IndentedTextWriter writer = new IndentedTextWriter(new StreamWriter(OutputName, false), " ");
try
{
CodeProvider.GenerateCodeFromCompileUnit(Unit, writer, new CodeGeneratorOptions());
writer.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
writer.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

// Create the compiler options
// Include referenced assemblies
CompilerParameters Options = new CompilerParameters();
Options.GenerateExecutable = true;
Options.OutputAssembly = "TestForm1.exe";
Options.CompilerOptions = "/target:winexe";
Options.MainClass = "Test.CreateForm.Form1";

string[] referenceAssemblies = { "System.dll", "System.Data.dll", "System.Drawing.dll", "System.Windows.Forms.dll", "System.XML.dll" };

Options.ReferencedAssemblies.AddRange(referenceAssemblies);

//Build and look for compiler errors
CompilerResults Result = CodeProvider.CompileAssemblyFromFile(Options, "Some.cs");

if (Result.Errors.Count > 0)
{
foreach(CompilerError ce in Result.Errors)
{
Console.WriteLine(ce.ErrorText);
}

}
else
{
Console.WriteLine("compiled successfully");
}

Console.WriteLine("press enter to continue");
Console.ReadLine();
}

最佳答案

您有很多创建空 CodeExpression 的实例,例如在构造函数代码中:

        // Create the constructor and add code
CodeConstructor Constructor = new CodeConstructor();

Constructor.Statements.Add(
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression(), "InitializeComponent", new CodeExpression() { }));

如果您不想将任何参数传递给该方法(上面代码中就是这种情况),只需不传递任何东西(CodeMethodInvokeExpression 构造函数采用 params[] 数组,因此如果您不传递任何东西,这意味着它接收到一个空数组):

        // Create the constructor and add code
CodeConstructor Constructor = new CodeConstructor();

Constructor.Statements.Add(
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression(),
"InitializeComponent"));

关于c# - 尝试使用 Codedom 生成代码时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6603028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com