質問

I have a class that has two boolean properties - A,B.

I want to add a restriction such that A and B cannot be false at the same time. Is there some attribute I can apply to the Class such that A=false and B = false becomes invalid?

役に立ちましたか?

解決

There's nothing built in. You're going to need to write this logic yourself. There are three ways to do so, in declining order of "good practice":

  1. Replace both with an enum: When you have two mutually exclusive states, you're better off combining them into a single value that has multiple states. If you really need them as separate booleans, you can write get-only properties which check the central state.

    public enum MyState
    {
        NoState,
        IsStateA,
        IsStateB,
    }
    public MyState State { get; set; }
    public bool IsStateA { get { return State == MyState.IsStateA; } }
    public bool IsStateB { get { return State == MyState.IsStateB; } }
    
  2. Enforce it in the business logic layer: In this case, you just enforce the restriction in the UI, or wherever the input is coming from. Whenever you try and toggle one, you check the state of the other and notify/alter appropriately.

  3. Write setter logic to toggle the other: When one is set, set the other.

    private bool _StateA;
    private bool _StateB;
    public bool IsStateA { 
      get { return _StateA; }
      set { 
        _StateA = value;
        if (value) _StateB = false; // If this is now true, falsify the other.
      }
    }
    public bool IsStateB { 
      get { return _StateB; }
      set { 
        _StateB = value;
        if (value) _StateA = false; // If this is now true, falsify the other.
      }
    }
    

Choice #1 is really the best way to handle a "three state" situation like this, but the others will also work.

他のヒント

why not use simple get/set logic?

private bool a;

public bool A
{
    get { return a; }
    set 
    { 
        if (value == B)
        {
            throw new Exception("A and B have the same boolean value!");
        }
        else
            a = value;
    }
}

or allow A and B to be set in either state regardless but have a third boolean for storing logic validity:

public bool IsValid { get { return (A == B); } }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top