我这样做:
var doc = new XPathDocument(Application.StartupPath + "/InfoR.xml");
var navigator = doc.CreateNavigator();
var Name = navigator.SelectSingleNode("//appsettings/name");
var user = navigator.SelectSingleNode("//appsettings/user");
var PPs = navigator.SelectSingleNode("//appsettings/PPs");
var aze = navigator.SelectSingleNode("//appsettings/aze");
我试图在公共部分课上阅读这些内容。所以我可以从我的应用程序的任何地方访问Name,用户等。 (Form1.cs的) 但正如我所看到的,不能在那里制作var ...不像int,string,float,....
答案 0 :(得分:3)
这不可能像你这样做。 var
用于方法的本地变量,而不是类。您需要在类级别声明这些变量:
private XPathNavigator Name;
private XPathNavigator user;
private XPathNavigator PPs;
private XPathNavigator aze;
然后用这个方法:
this.Name = navigator.SelectSingleNode("//appsettings/name");
this.user = navigator.SelectSingleNode("//appsettings/user");
this.PPs = navigator.SelectSingleNode("//appsettings/PPs");
this.aze = navigator.SelectSingleNode("//appsettings/aze");
然后该类中的其他方法或其他地方的部分朋友可以访问它。
答案 1 :(得分:2)
如果要在方法中声明这些变量,则只能在该方法中访问它们。如果要在表单中的其他方法中使用它们,则需要将它们声明为成员变量。类似的东西:
public partial class Form1 : Form
{
XPathNavigator Name;
XPathNavigator user;
XPathNavigator PPS;
XPathNavigator aze;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var doc = new XPathDocument(Application.StartupPath + "/InfoR.xml");
var navigator = doc.CreateNavigator();
Name = navigator.SelectSingleNode("//appsettings/name");
user = navigator.SelectSingleNode("//appsettings/user");
PPs = navigator.SelectSingleNode("//appsettings/PPs");
aze = navigator.SelectSingleNode("//appsettings/aze");
}
}
答案 2 :(得分:0)
正如我正确理解你的问题,你很可能正在寻找这样的东西(例如如何检索节点并将其存储到属性中):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string Name { get; set; }
private void button1_Click(object sender, EventArgs e)
{
XPathDocument document = new XPathDocument(Application.StartupPath + "/InfoR.xml");
XPathNavigator navigator = document.CreateNavigator();
XPathNavigator node = navigator.SelectSingleNode("//appsettings/name");
Name = node.InnerXml;
}
}