净 - 策略以避免魔术字符串 [英] .Net - Strategies to avoid magic string

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

问题描述

在code在工作中,我们有一个神奇的字符串,如以下code段很多用途:

In code at work, we have many uses of magic strings like the following code snippet:

if (user.HasRight("Profile.View")) {...}

因此​​,有在那里我们传递字符串作为参数来查看用户是否具有特定的权利许多地方。我不喜欢这样,因为这会产生很多神奇的字符串。

So there are many places where we pass a string as a parameter to see if the user has a specific right. I don't like that because that generates a lot of magic strings.

什么是做一个更好的办法?

What would be a better way of doing it?

枚举,常量,类?

推荐答案

在特定情况下,使用一个枚举。不会有神奇的字符串,如果枚举的变化(在某种程度上会破坏魔术字符串的解决方案),应用程序将不再进行编译。

In that specific case, use an Enum. There will be no magic strings and if the Enum changes (in a way that would break the magic strings solution), the app will no longer compile.

public enum ProfilePermissions
{
    View,
    Create,
    Edit,
    Delete
}

然后,你可以简单地有:

Then you can simply have:

if(user.HasRight(ProfilePermissions.View)) { }

您也可以使用一类,但你限制自己,当涉及到更复杂的情况。例如,枚举的一个简单的改变是这样的:

You could also use a class, but then you limit yourself when it comes to more complex scenarios. For instance, a simple change of the Enumeration to something like:

public enum ProfilePermissions
{
    View = 1,
    Create = 2,
    Edit = 4,
    Delete = 8
}

(其中用户需要创建或删除例如,一种情况)将允许您使用按位运算符用于更复杂的权限:

Would allow you to use bitwise operators for more complex permissions (for example, a situation where a user needs either Create or Delete):

if(user.HasRight(ProfilePermissions.Create | ProfilePermissions.Delete));

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

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