【发布时间】:2016-06-01 14:54:57
【问题描述】:
我想了解如何使用 c# 构建文件,因此我创建了一个 Windows 窗体应用程序并创建了这个代码/表单。但它似乎没有用。
.
using System;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
namespace teztie
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "*.exe |*.exe";
DialogResult result = sfd.ShowDialog();
if (result == DialogResult.OK)
{
build(sfd.FileName, textBox1.Text, textBox2.Text);
}
}
private void build(string output, string msg, string name)
{
CompilerParameters p = new CompilerParameters();
p.GenerateExecutable = true;
p.ReferencedAssemblies.AddRange(new string[] { "System.dll", "System.Windows.Forms.dll"});
p.OutputAssembly = output;
p.CompilerOptions = "/t:winexe";
string source = Properties.Resources.source;
string errors = string.Empty;
source = source.Replace("[MSG]", msg);
source = source.Replace("[NAME]", name);
CompilerResults results = new CSharpCodeProvider().CompileAssemblyFromSource(p, source);
if (results.Errors.Count > 0)
{
foreach (CompilerError err in results.Errors)
{
errors += "Error: " + err.ToString() + "\r\n\r\n";
}
}
else
{
errors = "Successfully built:\n" + output;
}
MessageBox.Show(errors, "Build", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
来源.txt:
using System;
using System.Windows.Forms;
namespace code
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("[msg]", "[title]" );
}
}
}
但是当我点击编译按钮时,它给了我一个错误。 当前上下文中不存在名称 InitializeComponent。
【问题讨论】:
-
尝试将所有内容放在同一个命名空间中
-
您已更改 Form1.cs 文件中的命名空间,但此文件包含部分类。您的课程的其余部分位于名为 Form1.designer.cs 的文件中。您将在那里找到 InitializeComponent,但现在命名空间不同,编译器找不到它。在 Designer.cs 文件中也修复命名空间