我怎么不坚持全局变量的数据? [英] How do I persist data without global variables?

查看:114
本文介绍了我怎么不坚持全局变量的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经习惯了脚本语言。 PHP,Java脚本等,我已经写了一些相对简单的Java和C#应用程序。这是一个问题,我已经多次需要一个答案,和我想象我不是唯一的一个。

I'm used to scripting languages. PHP, Javascript etc. and I've written a few relatively simple Java and C# apps. This is a question I've repeatedly needed an answer for, and I imagine I'm not the only one.

比方说,我在Javascript。

Let's say I'm in Javascript.

我有函数A(),由GUI,它检索一些值调用。

I have function A(), called by the GUI, which retrieves some value.

函数b(),也由GUI调用,要求的值,但是函数b()将被称为倍)的任意数,时间A之后的任意长度(

Function B(), also called by the GUI, requires that value, but function B() is going to be called an arbitrary number of times, an arbitrary length of time after A().

我不希望A()每次重新计算值。

I don't want A() to recalculate the value every time.

一个例子是登录凭据。 A()询问用户名和B()使用该值每次调用时追加到日志中。

An example is logon credentials. A() asks for a username, and B() uses that value to append to a log every time it is called.

有关这个我可能会只使用一个全球性的变量。

For this I would probably just use a global variable.

现在,C#。没有全局变量!我怎么做到这一点。

Now, C#. No global variables! How am I supposed to do this?

编辑:
享有的答案,但也有很多的尽量不使用全局变量的意见。这一点我理解,但我想听听这一要求的替代模式。

Enjoying the answers, but there are a lot of "try not to use globals" comments. Which I do understand, but I'd like to hear the alternative patterns for this requirement.

推荐答案

首先,总是问自己,如果你真的需要有一个全球性的,往往你不会。但是,如果你真的有一个...

Firstly, always ask yourself if you really need to have a global, often you won't. But if you really have to have one...

要做到这一点,最好的办法是有一些理智命名的类的静态属性,它有效地成为你的全局变量

The best way to do this is to have a static property on some sensibly named class, it effectively becomes your global variable

public class Credentials
{
  public static string Username {get;set;}
}

//...somewhere in your code

Credentials.Username = "MyUserName";



编辑:

一对夫妇的人在这里说毯声明全局变量是坏的,我也有这种看法一致,并且它会出现C#的设计师也同意,因为他们根本就没有用。

A couple people here have said the blanket statement that Global Variables are bad, and I do agree with this sentiment, and it would appear that the designers of C# also agree as they are simply not available.

我们应该然而,看看为什么全局不好的原因,他们大多认为是不好的,因为你破坏了封装的规则。静态数据虽然不necesarrily不好,是静态数据的好处是,你可以封装它,我上面的例子就是一个非常简单的例子,可能在真实的场景,你将包括在同一类的静态数据确实有凭据,也许登录类或User类或任何有意义的您的应用程序的其它工作。

We should however look at the reasons why Globals are bad, and they are mostly regarded as bad because you break the rules of encapsulation. Static data though, is not necesarrily bad, the good thing about static data is that you can encapsulate it, my example above is a very simplistic example of that, probably in a real world scenario you would include your static data in the same class that does other work with the credentials, maybe a Login class or a User class or whatever makes sense to your app.

这篇关于我怎么不坚持全局变量的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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