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

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

问题描述

什么是用于在VB.NET WinForms应用程序存储的全局变量的最佳实践。例如,当你可能需要一个用户登录到一个应用程序来存储它可以在整个应用程序进行访问的的currentUser对象。你可以存储这个作为一个模块的对象或创建一个包含成员所有需要的全局类,你仍然需要尽管存储在某个地方的实例。

What's the best practise 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.

直接从'环法自行车部队'code完成以下几个原因利用全球数据:

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

  • $ P $全球价值pservation
  • 简化使用极为普遍 数据
  • 在消除流浪汉数据
  • Preservation of global values
  • Streamlining use of extremely common data
  • Eliminating tramp data

麦康奈尔还说:

使用全局数据只作为最后的手段。   在你诉诸使用全球   数据,考虑一些替代品。

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

我在这里提到的事情得到很大的覆盖面,在梦幻般的书 code完整

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

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

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