.Net - 避免魔术字符串的策略

发布于 2024-09-09 03:58:49 字数 206 浏览 3 评论 0原文

在工作代码中,我们有很多使用魔术字符串的情况,如下面的代码片段:

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

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

更好的方法是什么?

枚举、常量、类?

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?

Enum, Constant, class ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

森林迷了鹿 2024-09-16 03:58:49

在这种特定情况下,请使用枚举。不会有魔术字符串,如果枚举发生变化(以破坏魔术字符串解决方案的方式),应用程序将不再编译。

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

然后你可以简单地拥有:

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

你也可以使用一个类,但是当涉及到更复杂的场景时你就会限制自己。例如,将枚举简单更改为:

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

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

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

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));
嘿看小鸭子会跑 2024-09-16 03:58:49

这在 .NET 框架中也很常见。示例包括 System.Windows.DataFormats 和 System.Net.WebRequestMethods.Http。您需要只读品种:

public static class MumbleRights {
  public static readonly string ProfileView = "Profile.View";
  // etc..
}

This is common enough in the .NET framework as well. Examples are System.Windows.DataFormats and System.Net.WebRequestMethods.Http. You'd want the readonly variety:

public static class MumbleRights {
  public static readonly string ProfileView = "Profile.View";
  // etc..
}
jJeQQOZ5 2024-09-16 03:58:49

扩展方法!将它们放在同一个地方以跟踪所有魔法弦。

public static class UserRightsExtensions {
  public static bool CanReadProfile(this User user)
  {
    return user.HasRight("Profile.View");
  }

  // etc..
}

然后你可以:

if (user.CanReadProfile()) .....

Extension methods! Keep them in the same place to keep track of all magic strings.

public static class UserRightsExtensions {
  public static bool CanReadProfile(this User user)
  {
    return user.HasRight("Profile.View");
  }

  // etc..
}

Then you can:

if (user.CanReadProfile()) .....
壹場煙雨 2024-09-16 03:58:49

创建一个对这些属性进行强类型化的类,例如

public static class UserInfo
{
  public static bool CanViewProfile { get { return User.HasRight("Profile.View"); } }
}

这会将您的“魔术字符串”保留在代码中的一个位置。枚举也可以工作,但在我看来可读性较差。

注意:我的示例旨在充当登录用户的属性代理,即静态类。如果您想要一些可以处理更直接的数据(例如,用户列表)的东西,这种类型的类需要是非静态的,并在每个用户帐户的基础上实例化。

Create a class which strongly-types those properties, like

public static class UserInfo
{
  public static bool CanViewProfile { get { return User.HasRight("Profile.View"); } }
}

This will keep your "magic strings" in one place within your code. An enum will also work, but isn't as readable in my opinion.

Note: my example is intended to act as a property proxy for the logged in user, thus the static class. If you wanted something that would work on more immediate data (say, a list of users), this type of class would need to be non-static and instantiated on per-user-account basis.

梦在夏天 2024-09-16 03:58:49

您可以在 C# 中执行常量字符串。

您可以像这样定义标头中的所有字符串:

const string PROFILE_VIEW "Profile.View";

不确定这是否是“最佳”方式,但它肯定比在代码中包含魔法值更好。

You can do constant strings in C#.

You could define all of the strings in a header like this:

const string PROFILE_VIEW "Profile.View";

Not sure if this is the "best" way, but its certainly better than having magic values in the code.

旧城空念 2024-09-16 03:58:49

我赞同“Justin Niessner”所展示的方式。但在某些情况下,我宁愿编写以下代码结构。

public  class User
    {
        public Permission Permission { get; set; }

    }
    public abstract class Permission
    {

    }
    public class ViewPermission:Permission
    {

    }

你可以把它当作

User user=new User();
            if(user.Permission is ViewPermission)
            {

            }

I second the way shown by "Justin Niessner". But in some cases I would rather prefer writing following construct of code.

public  class User
    {
        public Permission Permission { get; set; }

    }
    public abstract class Permission
    {

    }
    public class ViewPermission:Permission
    {

    }

and you can consume it as

User user=new User();
            if(user.Permission is ViewPermission)
            {

            }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文