使用其他方法C#中的变量 [英] use variable from other method C#
问题描述
C#编程的新手,非常缺乏经验
new to C# programming and very unexperienced
我正在创建一个带有文本框的表单,我希望我的程序在一个方法中读取该框中的数字,并在其他方法中使用这些数字执行操作,这就是现在的样子
i'm creating a form with a text box, i want my program to read numbers in that box in a method, and execute operation with those numbers in other 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 on 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屋!