在C#中使用另一个方法的变量 [英] Use a variable from another method in C#
问题描述
我是C#编程的新手,而且经验不足.
I am new to C# programming and am very inexperienced.
我正在创建一个带有文本框的表单,我希望程序在一种方法中读取该框中的数字,并在另一种方法中使用这些数字执行操作.现在是这样的:
I'm creating a form with a text box, and I want my program to read numbers in that box in a method, and execute an operation with those numbers in another method. Here's how it is by now:
public void readG_TextChanged(object sender, EventArgs e)
{
string _G = readG.Text;
decimal _Gd = Convert.ToDecimal(_G);
}
public void readQ_TextChanged(object sender, EventArgs e)
{
string _Q = readQ.Text;
decimal _Qd = Convert.ToDecimal(_Q);
}
private void button1_Click(object sender, EventArgs e)
{
decimal _ULS = (1.35m * _Gd + 1.5m * _Qd);
Console.WriteLine("{0}", _ULS);
}
readQ , readG 是方框名称. button1 是继续进行操作并在控制台中显示的按钮.
readQ, readG are the boxes names. button1 is the button to proceed to the operation, and display it in a console.
到目前为止,我在button1_click方法中没有_Gd和_Qd上下文.除此之外,我认为它会很好运行.
So far I have the _Gd and _Qd out of context in the button1_click method. Besides that, I think it will run pretty fine.
推荐答案
You should read up on scoping... http://msdn.microsoft.com/en-us/library/ms973875.aspx
一种方法是将_Qd和_Gd置于类级别,而不是在方法本身中定义,以便您可以在click方法中访问它们.
One way is for your _Qd and _Gd to be at the class level, not defined within the methods themselves, so that you have access to them in the click method.
private decimal _Gd;
private decimal _Qd;
public void readG_TextChanged(object sender, EventArgs e)
{
string _G = readG.Text;
_Gd = Convert.ToDecimal(_G);
}
public void readQ_TextChanged(object sender, EventArgs e)
{
string _Q = readQ.Text;
_Qd = Convert.ToDecimal(_Q);
}
private void button1_Click(object sender, EventArgs e)
{
decimal _ULS = (1.35m * _Gd + 1.5m * _Qd);
Console.WriteLine("{0}",_ULS);
}
这篇关于在C#中使用另一个方法的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!