如何在全局变量中存储文本框值? [英] How Can I Store A Text Box Value In A Global Variable?

查看:89
本文介绍了如何在全局变量中存储文本框值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

i have a code like this :

int a;
                  a=Convert.ToDouble(textbox1.text);



我不能在另一个窗体或类中使用a变量。当我想要插入公共类中的代码在全局使用它的文本框是不可用的。任何正文都知道如何全局使用该变量或全局声明它而不将其插入类中?


and i cant use "a" variable in another windows form or class.when i want to insert the code in a public class to use it globally the text box is not available.does any body knows how to use that variable globally or declare it globally without inserting it in a class?

推荐答案

不要。

尽管有可能 - 你可以将它声明为静态类成员,正如Shmuel Zang所说,这通常证明设计不佳以及大量的kludge继续绕过它。主要是因为每个应用程序只有一个静态变量的单个实例,这意味着如果你尝试重新使用表单或代码,你将开始出现奇怪的错误。



一般来说,如果您创建了实例,则应将值传递给类(或表单),或者发出事件信号以允许创建者获取值并将其传递给相应的类。



看看这些:

在两种形式之间转移信息,第1部分:父母对儿童 [ ^ ]

在两种形式之间传递信息,第2部分:儿童到父母 [ ^ ]

在两种表格之间转移信息,第3部分:儿童与儿童 [ ^ ]

他们可能会以更友好的OOP方式覆盖你想要做的事情。
Don't.
While it's possible - you can declare it as a static class member as Shmuel Zang suggests, that's generally evidence of poor design and a massive kludge going on to get round it. Mostly because there is only ever one single instance of a static variable per application, and that means that if you ever try to re-user you form or code, you will start to get strange errors creeping in.

Generally speaking you should pass the value to the class (or form) if you created the instance, or signal an event to allow your "creator" to fetch the value and pass it to the appropriate class.

Have a look at these:
Transferring information between two forms, Part 1: Parent to Child[^]
Transferring information between two forms, Part 2: Child to Parent[^]
Transferring information between two forms, Part 3: Child to Child[^]
They will probably cover what you are trying to do in a more OOPs friendly way.


你可以将它定义为静态类成员。

例如,您可以创建一个静态类来保存全局使用的所有变量:

For instance, you can create a static class for holding the whole of the variables that are used globally:

static class MyGlobals
{
    public static double a;
}

然后,您可以在表单中使用它,以及其他形式:

Then, you can use it in your form and, in other forms:

MyGlobals.a = Convert.ToDouble(textbox1.text);


这篇关于如何在全局变量中存储文本框值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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