C# “must declare a body because it is not marked abstract, extern, or partial”

前端 未结 7 599
轻奢々
轻奢々 2020-12-15 15:05

I\'m not sure why i\'m getting this error to be honest.

private int hour
{
    get;
    set
    {
        //make sure hour is positive
        if (value <         


        
7条回答
  •  别那么骄傲
    2020-12-15 15:28

    You need to provide a body for the get; portion as well as the set; portion of the property.

    I suspect you want this to be:

    private int _hour; // backing field
    private int Hour
        {
            get { return _hour; }
            set
            {
                //make sure hour is positive
                if (value < MIN_HOUR)
                {
                    _hour = 0;
                    MessageBox.Show("Hour value " + value.ToString() + " cannot be negative. Reset to " + MIN_HOUR.ToString(),
                    "Invalid Hour", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    //take the modulus to ensure always less than 24 hours
                    //works even if the value is already within range, or value equal to 24
                    _hour = value % MAX_HOUR;
                }
            }
        }
    

    That being said, I'd also consider making this code simpler. It's probably is better to use exceptions rather than a MessageBox inside of your property setter for invalid input, as it won't tie you to a specific UI framework.

    If that is inappropriate, I would recommend converting this to a method instead of using a property setter. This is especially true since properties have an implicit expectation of being "lightweight"- and displaying a MessageBox to the user really violates that expectation.

提交回复
热议问题