简体   繁体   English

如何在C#中实现自动实现的属性以设置值

[英]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.Visible = true;
            }
        }
    }

You must implement both a getter and setter if you implement one of them. 如果实现其中之一,则必须同时实现getter和setter。 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;
      //...
   }
}

自动实现仅适用于设置和获取没有自定义主体的简单用例

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. 另外,您的get可以从集合中正在修改的按钮的状态推断出值-但这开始变得愚蠢了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM