Вопрос

I'm trying to use a property to prevent the first value of a list ever being less than zero:

    private List<int> _MyList = new List<int>();
    public List<int> MyList
    {
        get
        {
            return _MyList;
        }
        set
        {
            if (value[0] < 0)
            {
                value[0] = 0;
            }

            _MyList = value;
        }
    }

Add then in my code:

if(ButtonPressed)
{
      MyList[0] -= 1;
}

However I can press the button and decrease the value through zero.

What am I missing?

Это было полезно?

Решение

You never enter that property, it is reserved for setting the value of the actual list rather than the lists elements. Your best bet is to write a method to reduce the items count

void AdjustCount(int value)
{
    if(MyList[0] + value >= 0)
        MyList[0] += value
}


if(ButtonPressed)
{
   AdjustCount(-1);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top