在 C# 中使用另一个方法中的变量 [英] Use a variable from another method in C#

查看:21
本文介绍了在 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.

推荐答案

您应该仔细阅读范围... http://msdn.microsoft.com/en-us/library/ms973875.aspx

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆