[本文发布于https://blog.youkuaiyun.com/Stack_/article/details/122991639,未经许可不得转载,转载须注明出处]
一、新建项目后,默认的文件
二、 在解决方案上右键选择添加一个类,重命名后点击添加
三、 得到SP.cs文件
四、 Form1.cs文件内有2个控件,点击button1,成功输出OK字符串到textBox1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "OK";
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
五、 SP.cs文件默认代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
class SP
{
}
}
六、 对SP.cs文件进行修改
SP.cs文件引入using System.Windows.Forms;,
命名空间保持一致,并添加partial 关键字,类名修改为与Form1.cs的一致,
将button1_Click剪切过来
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Test
{
public partial class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "OK";
}
}
}
也成功输出了OK字符串
七、 让SP.cs文件挂到Form1.cs下(走完上面的步骤已经能用了,下面不必要)
<Compile </Compile标识符格式为
<Compile xxxxxx>
xxxxxxxxx
</Compile>
或者
<Compile xxxxxx />
<Compile xxxxxx />
<Compile xxxxxx />
n多个
<Compile xxxxxx />
<Compile xxxxxx > 最后这个不带斜杠
</Compile>
格式错误将无法加载项目
SP.cs上右键>打开方式,选择CSharp编辑器,并设为默认值后确定;
若选择为CSharp窗体编辑器,打开SP.cs时会多出一个窗体,并且编译时可能会报错:两个输出文件名解析为同一个输出路径:“obj\x86\Debug\xxx.resources” ,此时需要删除SP.cs文件的.resx后缀子文件。