Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

c# - How do I persist data without global variables?

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.

Let's say I'm in Javascript.

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

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().

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

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.

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

Edit: 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is not a good practice, but if you really need it, there is a number of ways:

  1. Web apps: You can put your variable in some kind of context, like the session or the application scope.
  2. Desktop apps: You can create an object and store it as a property of a class that always have an object active.
  3. Any kind of app: use a public static property. It is visible to everyone.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...