在代码中使用大量硬编码的字符串 [英] Using a lot of hardcoded strings in code

查看:44
本文介绍了在代码中使用大量硬编码的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我查看我的代码时,我正在写类似..

When I am looking at my code and I am writing things like..

if (role == "Customer")
{
    bCustomer = true;
}
else if (role == "Branch")
{
    bIsBranch = true;
}

foreach(DataRow as row in myDataSet.Tables[0].Rows)
{
    row["someField"]=somefield.Tostring()
}

你们在这样做吗?什么时候可以这样做,什么时候不应该这样做?如果有的话,写它的更好方法是什么?

Are you guys doing this? When is this ok to do and when shouldn't you be doing this? What if any would be a better approach to write this if any?

感谢您的评论:我猜我应该添加一次(如果出于此示例目的)我只使用一次此角色比较?开设一个全新的课堂仍然是一个更好的主意吗?另外,我是否应该有1个称为常量"的类,它们是持有特定常量的多个类,例如角色"类?

Thanks For the Comments: I guess I should add what if (for this example purposes) I am only using this role comparison once? Is it still a better idea to make a whole new class? Also should I have 1 class called "constants" are multiple classes that that hold specific constants, like "roles" class for example?

推荐答案

否.不要使用"神奇的字符串".而是创建一个带有常量的静态类,或者如果可能的话,创建一个枚举.

No. Don't use "magic strings". Instead create a static class with constants, or an enum if you can.

例如:

public static class Roles
{
  public const string Customer = "Customer";
  public const string Branch = "Branch";
}

用法:

if (role == Roles.Customer)
{

}
else if (role == Roles.Branch)
{

}

这是关于各种解决方案的精彩讨论.

这篇关于在代码中使用大量硬编码的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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