简体   繁体   English

在类之间编写共享枚举的最佳实践是什么?

[英]What's the best practice to code shared enums between classes

namespace Foo
{
    public enum MyEnum
    {
        High, Low
    }

    public class Class1
    {
        public MyEnum MyProperty { get; set; }
    }
}

MyEnum is declared outside Class1 cause I need it here and in other classes MyEnumClass1之外声明,因为我需要它和其他类

Seems good, but what if I decide later to delete the file containing Class1 ? 看起来不错,但如果我稍后决定删除包含Class1的文件怎么办?

MyEnum declaration will be lost!! MyEnum声明将丢失!!

What's the best practice to code shared enums between classes? 在类之间编写共享枚举的最佳实践是什么?

The best practice is creating separate file for each class, enum, or other type. 最佳实践是为每个类,枚举或其他类型创建单独的文件。

MyEnum.cs MyEnum.cs

namespace Foo
{
    public enum MyEnum
    {
        High, 
        Low
    }
}

Class1.cs 将Class1.cs

namespace Foo
{
    public class Class1
    {
        public MyEnum MyProperty { get; set; }
    }
}

What's the best practice to code shared enums between classes? 在类之间编写共享枚举的最佳实践是什么?

Have your enumerations each in a file of its own, with the same name as the enumeration. 将每个枚举放在一个自己的文件中,其名称与枚举相同。

// Foo\MyEnum.cs
namespace Foo
{
    public enum MyEnum
    {
        High, Low
    }
}

From my experience it is also good to add explicit values to fields in case you store them in database as integers, because changing the order or adding/deleting value in between may end up in runtime fail: 根据我的经验,如果将显式值作为整数存储在数据库中,也可以向字段添加显式值,因为更改顺序或在中间添加/删除值可能最终会在运行时失败:

namespace Foo
{
    public enum MyEnum
    {
        High = 1, 
        Low = 2
    }
}

Also notice I start from 1 to be aware that uninitialized variable is not treated as correct enum value. 另请注意,我从1开始意识到未初始化的变量不被视为正确的枚举值。 Another idea is to add None = 0 value. 另一个想法是添加None = 0值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM