简体   繁体   English

如何实现属性的一系列常量预定义“状态”?

[英]How to implement a range of constant predefined “states” of a property?

I have a property LegalCaseStatus .我有一个财产LegalCaseStatus My intention is to make the property to accept a predefined range of approved values.我的意图是使属性接受预定义的批准值范围。 The range must be visible and unchanged throughtout my program.该范围必须在我的整个程序中可见且不变。 Here's an example of the list:这是列表的示例:

Plaintiff
Defendant
Third Party
Debitor
Creditor
Petitioner

So, the best way I could think of is to declare a static class, and fill it with corresponding constants:所以,我能想到的最好方法是声明一个 static class,并用相应的常量填充它:

public static class Participants
{
    public const byte 
        Piaintiff = 0, 
        Defendant = 1, 
        ThirdParty = 2, 
        Debitor= 3, 
        Creditor = 4, 
        Petitioner = 5;
}

so after using a namespace I could just do:所以在使用命名空间后,我可以这样做:

public byte LegalCaseStasus = Plaintiff;

the only problem is, since it's just a byte member it'll accept anything that is byte :唯一的问题是,因为它只是一个byte成员,它会接受任何byte

LegalCaseStatus = 99; // ok
LegalCaseStatus = SomeOtherByteConstant; // ok

How do I protect the member LegalCaseStatus ?我如何保护会员LegalCaseStatus Is my solution generally correct?我的解决方案通常正确吗?

You can use enums - An enum is a special "class" that represents a group of constants (unchangeable/read-only variables).您可以使用枚举 -枚举是一个特殊的“类”,它代表一组常量(不可更改/只读变量)。 Sounds like the thing you describe in your question:听起来像您在问题中描述的内容:

public enum Participants
{
        Piaintiff = 0,
        Defendant = 1,
        ThirdParty = 2,
        Debitor = 3,
        Creditor = 4,
        Petitioner = 5
}

After the enum definition you can use it exactly the way you want to:在枚举定义之后,您可以完全按照您想要的方式使用它:

Participants LegalCaseStasus = Participants.ThirdParty;
LegalCaseStasus = 99;   // ERROR      
byte underlying_value = (byte)LegalCaseStasus; // value == 2

Note: The underlying value of an enum is int !注意: enum的基础值是int When you cast to byte you need to make sure there are no predefined values that exceed the byte limit.当您转换为byte时,您需要确保没有超过byte限制的预定义值。

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

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