开发者

how to implement autoimplemented properties in C# for setting a value

I am trying to use autoimplemented properties. It shows me error

    public OpenMode OpenFor
    {
        get;//must declare a body because it is not marked as abstract, partial or external. Why so 
        set
        {
            if (value == OpenMode.Add)
            {
                btnAddGuest.Text = "Save";
                btnUpdatePreference.Visible = false;
                dgvGuestInfo.ClearSelection();
            }
            else if (value == OpenMode.Update)
            {
                btnAddGuest.Text = "Update";
                btnUpdatePreference.V开发者_StackOverflow中文版isible = true;
            }
        }
    }


You must implement both a getter and setter if you implement one of them. You can auto implement only both:

public OpenMode OpenFor
{
   get; 
   set;
}

You may consider to use a backing field:

private OpenMode openFor;

public OpenMode OpenFor
{
   get
   {
      return openFor;
   }
   set 
   {
      openFor = value;
      //...
   }
}


autoimplementation works only for the simple usecase that set and get have no custom body


To use just get; you need to use just set; as well. In this case you'd have an implicit variable. When you declare a body for set, that doesn't work. Ask yourself the question; how can you get anything you can never set?


private OpenMode _openFor;
public OpenMode OpenFor
{
    get{return _openFor;}
    set{
        _openFor = value;
        SetOpenFor(value);
    }
}

private void SetOpenFor(OpenMode mode)
{
 if (mode== OpenMode.Add)
 {
     btnAddGuest.Text = "Save";
     btnUpdatePreference.Visible = false;
     dgvGuestInfo.ClearSelection();
 }
 else if (mode == OpenMode.Update)
 {
     btnAddGuest.Text = "Update";
     btnUpdatePreference.Visible = true;
 }
}


Also note that the auto-implemented properties also listen to access modifiers:

public string Foo { get; private set; }

Though you still need to define both.

In your example, it looks like you don't need the get. You aren't storing the value into a local field either, so it looks like your property should be a method.

Alternatively, your get could infer the value from the state of the buttons you are modifying in the set - but this is starting to get silly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜