开发者

One to many Enum in C#

开发者 https://www.devze.com 2023-03-03 10:10 出处:网络
I have this 2 enum that I need to relate PendingStatus to TransactionStatus To explain, for each transaction there is one single status that I use TransactionStatus enum for, then for each Transactio

I have this 2 enum that I need to relate PendingStatus to TransactionStatus

To explain, for each transaction there is one single status that I use TransactionStatus enum for, then for each TransactionStatus there is many pending reasons that I use PendingStatus enum for?

    /// <summary>
/// Represent all available status for Transaction
/// </summary>
public enum TransactionStatus
{
    New =0,
    Submitted =1,
    PendingStatus = 2,
    Accepted = 3,
    Rejected =4,
    InProgress =5,
    Completed=6,
    Failed=7,
    Canceled=8
}

/// <summary>
/// Represent all available pending status for Transaction
/// </summary>
public enum PendingStatus
{
    PendingA =0,
    PendingX 开发者_如何学Python=1,
    PendingY = 2,
}   

How can I approach that?


You can use enum values as bitflag, as explained here.

This way you can mix PendingStatus and TransactionStatus together.

/// <summary>
/// Represent all available status for Transaction
/// </summary>
[Flags]
public enum TransactionStatus
{
    New = 0,
    Submitted = 1,
    PendingStatus = 2,
    Accepted = 4,
    Rejected = 8,
    InProgress = 16,
    Completed = 32,
    Failed = 64,
    Canceled = 128
}

/// <summary>
/// Represent all available pending status for Transaction
/// </summary>
[Flags]
public enum PendingStatus
{
    PendingA = 256,
    PendingX = 512,
    PendingY = 1024
}  

// Example to set transaction as accepted and pending

var MyTransactionStatus = Accepted & PendingA;

// How to check transaction is pendingA regardless of its status ?

if (MyTransactionStatus & PendingA == PendingA) ...


I would use the FlagsAttribute. So you could use a binary comparison.

[FlagsAttribute]
public enum TransactionStatus
{
    New = 0,
    Submitted = 1,
    PendingStatus = 2,
    Accepted = 4,
    // (...)
}

[FlagsAttribute]
public enum PendingStatus
{
    PendingA = 256,
    PendingX = 512,
    PendingY = 1024,
}
0

精彩评论

暂无评论...
验证码 换一张
取 消