.NET中的全局变量(或替代)最佳实践 [英] Global variable (or alternative) best practice in .NET

查看:188
本文介绍了.NET中的全局变量(或替代)最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在VB.NET WinForms应用程序中存储全局变量的最佳做法是什么?例如,当用户登录到应用程序时,您可能需要存储可在整个应用程序中访问的CurrentUser对象。您可以将它作为一个对象存储在模块中,或创建一个包含所有全局所需的成员的类,但您仍然需要将此实例存储在某个位置。



框架提供了一个简单的解决方案吗?

解决方案

我觉得'不'有点苛刻,这里有一个引用Steve McConnell:
$ b


与纪律一起使用时,全局变量
在几种情况下很有用


我认为就像一个优秀的木匠拥有正确的工具,并在需要时使用正确的工具,程序员也应该使用他们所有的工具处理。



直接从'Tour de Force'代码完成是使用全局数据的几个原因:


  • 保存全局值

  • 简化非常常见的
    数据的使用

  • 消除流量数据



McConnell也表示:


仅将全局数据作为最后的手段。
在使用全球
数据之前,请考虑几种选择。


这里是他列出的替代品:


  • 首先让每个变量局部变量
    ,并且仅当您需要变量时变量为全局变量

  • 区分全局和类
    变量

  • 使用访问例程


我在这里提到的东西在精彩的书籍代码完整中得到了很好的报道


What's the best practice for storing global variables in a VB.NET WinForms app. For example when a user logs into an app you may want to store a CurrentUser object which can be accessed throughout the app. You could store this as an object in a module or create a class which contains members for all the required globals, you would still need to store the instance of this somewhere though.

Does the framework provide an easy solution to this?

解决方案

I think 'don't' is a little harsh, here's a quote from Steve McConnell:

Used with discipline, global variables are useful in several situations

I think just like a good carpenter has the right tool for the job and will use the right tool if the need arises, programmers should also use all of the tools at their disposal.

Straight from the 'Tour de Force' Code Complete are several reasons to use global data:

  • Preservation of global values
  • Streamlining use of extremely common data
  • Eliminating tramp data

McConnell also says:

Use Global Data Only as a Last Resort. Before you resort to using global data, consider a few alternatives.

here are the alternatives he lists:

  • Begin by making each variable local and make variables global only as you need to
  • Distinguish between global and class variables
  • Use access routines

The things i've mentioned here get great coverage in the fantastic book Code Complete

这篇关于.NET中的全局变量(或替代)最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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