use variable from other method C#

后端 未结 2 465
刺人心
刺人心 2020-11-29 12:41

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 w

相关标签:
2条回答
  • 2020-11-29 13:31

    This concerns variable scope. The variables _Qd and _Gd only have scope within their methods.

    You could make them class members, that is declare them outside your methods, in the main body of the class, as follows:

     private decimal _Gd;
     private decimal _Qd;
    

    .

    Then you can set them like this:

     _Gd = Convert.ToDecimal(_G);
     _Qd = Convert.ToDecimal(_Q);
    

    These variables will be visible from within any method in your class.

    0 讨论(0)
  • 2020-11-29 13:34

    You should read up on scoping... http://msdn.microsoft.com/en-us/library/ms973875.aspx

    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);
    }
    
    0 讨论(0)
提交回复
热议问题