本文介绍了const int而不是枚举的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始在一个大型的c#代码库中工作,发现使用一个带有几个const ints字段的静态类。这个类的行为完全像一个枚举。

I started working on a large c# code base and found the use of a static class with several const ints fields. This class is acting exactly like an enum would.

我想将类转换成一个实际的枚举,但是这个权力被称为no。我想转换它的主要原因是我可以使用枚举作为数据类型而不是int。这可以帮助很多可读性。

I would like to convert the class to an actual enum, but the powers that be said no. The main reason I would like to convert it is so that I could have the enum as the data type instead of int. This would help a lot with readability.

有没有理由不使用枚举,而是使用const int?
这是当前的代码如何:

Is there any reason to not use enums and to use const ints instead?This is currently how the code is:

public int FieldA { get; set; }
public int FieldB { get; set; }

public static class Ids
{
    public const int ItemA = 1;
    public const int ItemB = 2;
    public const int ItemC = 3;
    public const int ItemD = 4;
    public const int ItemE = 5;
    public const int ItemF = 6;
}

但是,我认为应该是以下代码:

However, I think it should be the following instead:

public Ids FieldA { get; set; }
public Ids FieldB { get; set; }


推荐答案

我认为这里有很多答案忽略枚举的语义的含义。

I think many of the answers here ignore the implications of the semantics of enums.


  • 您应该考虑在整个所有有效值(Ids)集合提前知道时使用枚举,并且足够小以在程序代码中声明。

  • You should consider using an enum when the entire set of all valid values (Ids) is known in advance, and is small enough to be declared in program code.

如果一组已知值是所有可能值的子集,则应考虑使用int,而代码只需要注意此子集。

You should consider using an int when the set of known values is a subset of all the possible values - and the code only needs to be aware of this subset.

关于重构 - 在时间和业务限制允许的情况下,最好在新设计/实施对于以前的实施和风险在哪里被很好的理解。在利益低或风险高(或两者兼有)的情况下,最好采取不伤害的位置而不是不断改进 。只有你能够判断哪种情况适用于你的情况。

With regards to refactoring - when time and business contraints allow, it's a good idea to clean code up when the new design/implementation has clear benefit over the previous implementation and where the risk is well understood. In situations where the benefit is low or the risk is high (or both) it may be better to take the position of "do no harm" rather than "continuously improve". Only you are in a position to judge which case applies to your situation.

顺便说一句,既不是枚举或常量ints是一个好主意,当ID表示外部存储(如数据库)中的记录的标识符时。在程序逻辑中对这样的ID进行硬编码通常是有风险的,因为这些值在不同环境(例如,测试,开发,生产等)中可能实际上是不同的。在这种情况下,在运行时加载值可能是更合适的解决方案。

By the way, a case where neither enums or constant ints are necessarily a good idea is when the IDs represent the identifiers of records in an external store (like a database). It's often risky to hardcode such IDs in the program logic, as these values may actually be different in different environments (eg. Test, Dev, Production, etc). In such cases, loading the values at runtime may be a more appropriate solution.

这篇关于const int而不是枚举的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:54