C# 中的命名空间存在问题
本文关键字:存在 问题 命名空间 | 更新日期: 2023-09-27 18:20:07
...
using System.Xml;
namespace WindowsFormsApplication2
{
public partial class Form2 : Form
{
XmlDocument activeDoc=new XmlDocument();
public Form2(string path)
{
InitializeComponent();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
MessageBox.Show(Convert.ToString(sender),Convert.ToString(e));
}
private void button1_Click(object sender, EventArgs e)
{
save(path);
}
private void save(string path){
activeDoc.Save(path);
}
}
}
为什么button1_click函数说"'路径'元素在这种情况下不可用"?我确定 Form2 接收"路径",因为带有路径的诊断消息确实有效。
将路径分配给构造函数中的类变量,如下所示, 请注意,方法/构造函数的参数只能在该方法/构造函数的上下文中访问。无法从其边界的一侧访问。
string pathString = string.Empty;
XmlDocument activeDoc=new XmlDocument();
public Form2(string path)
{
pathString = path;
InitializeComponent();
}
你必须在项目中的某个地方声明路径。像这样做
...
using System.Xml;
namespace WindowsFormsApplication2
{
public partial class Form2 : Form
{
XmlDocument activeDoc=new XmlDocument();
String path;
public Form2(string _path)
{
path = _path;
InitializeComponent();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
MessageBox.Show(Convert.ToString(sender),Convert.ToString(e));
}
private void button1_Click(object sender, EventArgs e)
{
save(path);
}
private void save(string path){
activeDoc.Save(path);
}
}
}
类 Form2 中没有字段路径。例如,它可以是此命名空间中另一个类的静态字段。构造函数和保存方法将"路径"作为本地参数
像这样更改代码
public partial class Form2 : Form
{
XmlDocument activeDoc=new XmlDocument();
static string Localpath=null;
public Form2(string path)
{
InitializeComponent();
Localpath=path;
}
.....
现在
private void button1_Click(object sender, EventArgs e)
{
save(Localpath);
}