避免魔术字符串和数字 [英] Avoiding magic strings and numbers

查看:148
本文介绍了避免魔术字符串和数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究过去几年由各种程序员编辑的应用程序,并且我遇到了使用String Literals访问MenuItems的问题。

I am working on an application that has been edited by various programmers over the past few years and I have stumbled across a problem with using String Literals to access MenuItems.

例如:在许多地方有代码如

For Example: in many places there is code like

mainMenu.MenuItems[1].MenuItems[0].Visible=true;

mainMenu.MenuItems["View"].MenuItems["FullScreen"].Visible=true;




  1. 如何更改用于标识MenuItem的字符串并捕获它被用于访问的所有地方?菜单和菜单被声明为公开的,并且在整个大型应用程序中被使用。

  1. how do I change the Strings used to identify the MenuItem and catch all of the places that it is being used for access? The menus and menuitems are declared as public and are used throughout this large application

正确的方法是阻止使用这些魔术索引。每次添加新项目或更改名称时,我都会看到事情被破坏。

What is the right way prevent the use of these magic indexes from being used. I forsee things being broken everytime a new item is added or the name is changed.

我已经开始使用枚举字典方法,其中每个menuItem都与一个键配对。但这仍然不会迫使其他开发人员使用我的实现,也不是最优雅的解决方案2

P.S. I have started using an enumerated dictionary approach in which every menuItem is paired with a key. but this still does not force other developers to use my implementation nor is it the most elegant solution to question 2

推荐答案

给每个菜单在WinForms设计器中创建一个名称(我假设),然后通过该名称来引用它。

Give each menu item a name in the WinForms designer (I assume), and then refer to it by that name.

然后只需在代码中使用:

Then just use this in your code:

menuExit.Visible = false;






如果菜单项以编程方式添加,请执行此操作:


If the menu items are added programmatically, do this:

class MyForm : Form
{
    private MenuItem menuExit;

    ...

        myMenu.Items.Add(menuExit = new MenuItem(...));

    ...
}

然后仍然访问它通过 menuExit 名称。避免魔术数字和字符串的关键是只是直接引用你想要参考的内容。作为一个奖励,您现在可以使用F2安全地重命名这个vairable。

and then still access it by the menuExit name. The key to avoiding magic numbers and strings is to just keep a direct reference to whatever it is you want to refer to. As a bonus, you can now rename this vairable safely using F2.

这篇关于避免魔术字符串和数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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