开发者

How to set Multiple bool flags based on an int counter without iterating?

开发者 https://www.devze.com 2023-01-29 23:34 出处:网络
What is the best way to set my boolean properties based on an int counter property? So, lets say I have 10 boolean properties

What is the best way to set my boolean properties based on an int counter property?

So, lets say I have 10 boolean properties

public bool IsBool1 {get;set;}
....
public bool IsBool10 {get;set;}

and an int counter (which can never have a value greater than 10)

public int Counter {get;set;}

Finally, I have a method which sets the flags

private void SetFlagsByCounter(int counter)
{
  if (counter >= 1) { IsBool1 = true; }
  .....
  if (counter >= 10) { IsBool10 = true; }
}

Is there 开发者_如何学Pythona better way to set the flags instead of iterating the counter?


Do you actually need to have the 10 auto-properties? Could you have 10 properties which just return a value based on the counter? (Do you even need 10 properties in the first place?)

For example:

public class Foo
{
    public int Counter { get; set; }

    public bool IsBool1 { get { return Counter >= 1; } }
    public bool IsBool2 { get { return Counter >= 2; } }
    public bool IsBool3 { get { return Counter >= 3; } }
    public bool IsBool4 { get { return Counter >= 4; } }
    ...
}

Note that this differs from your original in 3 ways:

  • There's no SetFlagsByCounter method, just the property
  • In the original, if you called SetFlagsByCounter(10) and then SetFlagsByCounter(1), then IsBool5 (etc) would still return true, because you never cleared the flags.
  • In the original, SetFlagsByCounter didn't use (or change) the Counter property at all, in the code shown.

If you could give more context, it would be easier to help you.


Can you just use properties for the booleans?

public bool IsBool1
{
    get
    {
        return counter >= 1;
    }
}

public bool IsBool2
{
    get
    {
        return counter >= 2;
    }
}


If after all you still need to have 10 bool properties and a SetFlagsByCounter method, then the way to do it would be to define an internal array of bool as a backing value for the properties, like this:

class MyClass
{
    bool flags[] = new flags[10];

    public bool IsBool1 { get { return flags[0]; } set { flags[0] = value; } }
    public bool IsBool2 { get { return flags[1]; } set { flags[1] = value; } }
    ...
    public bool IsBool10 { get { return flags[9]; } set { flags[9] = value; } }

    public void SetFlagsByCounter(int counter)
    {
        for (int i = 0; i < counter; i++)
        {
            flags[i] = true;
        }
    }
}
0

精彩评论

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