我有正常工作代码:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
string name = tbxName.Text;
string age = tbxAge.Text;
string dinner = tbxDinner.Text;
}
private void OutputNewValues()
{
string answer = "Hello, " + tbxName.Text + " you are " + tbxAge.Text + " years old. " + tbxDinner.Text + " sounds yummy for dinner!";
finalOutput.Text = answer;
}
}
现在,在这一部分:
private void OutputNewValues()
{
string answer = "Hello, " + tbxName.Text + " you are " + tbxAge.Text + " years old. " + tbxDinner.Text + " sounds yummy for dinner!";
finalOutput.Text = answer;
}
我想使用我之前声明的字符串(名称,年龄,晚餐)而不是“tbxName.Text”。但它会给我一个错误,因为它在当前的上下文中不存在。
我该怎么做/我在哪里放置字符串部分以便在任何地方使用它?
答案 0 :(得分:0)
好的,你走了。
将文本框值作为参数传递给参数。
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
txtName.Text = "Your name";
tbxAge.Text = "Your age";
tbxDinner.Text = "Your dinner";
OutputNewValues(txtName.Text, tbxAge.Text, tbxDinner.Text);
}
private void OutputNewValues(string name, string age, string dinner)
{
string answer = "Hello, " + name + " you are " + age + " years old. " + dinner + " sounds yummy for dinner!";
finalOutput.Text = answer;
}
}
或使用成员变量:
public sealed partial class MainPage : Page
{
private string name = "Your name";
private string age = "Your age";
private string dinner = "Your dinner";
public MainPage()
{
this.InitializeComponent();
OutputNewValues();
}
private void OutputNewValues()
{
string answer = "Hello, " + name + " you are " + age + " years old. " + dinner + " sounds yummy for dinner!";
finalOutput.Text = answer;
}
}