【问题标题】:Error 1 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement错误1 只有assignment、call、increment、decrement、await、new object表达式可以作为语句使用
【发布时间】:2013-02-18 14:58:09
【问题描述】:
public partial class frmManager : Form
{
    public String Name
    {
        get 
        {
            txtName.Text;
        }
        set;
    }
}

错误1 只有赋值、调用、递增、递减、等待和new对象表达式可以作为语句使用

【问题讨论】:

    标签: c# .net properties frameworks windows-applications


    【解决方案1】:

    如果您想使用 getter 和 setter 并定义自定义 getter,您还需要定义自定义 setter。 例如:

        public String Name
        {
            get { return txtName.Text; }
            set { txtName.Text = value; }
        }
    

    或者你可以创建“getonly”属性:

        public String Name
        {
            get { return txtName.Text; }
        }
    

    【讨论】:

      【解决方案2】:

      您需要将其更改为:

      public partial class frmManager : Form
      {
          public String Name
          {
              get 
              {
                  return txtName.Text;
              }
              set;  // you may also want to change this to set the value of txtName.Text (txtName.Text = value)
          }
      }
      

      【讨论】:

        【解决方案3】:

        get 方法中需要return

        public partial class frmManager : Form
        {
            public String Name
            {
                get 
                {
                    return txtName.Text;
                }
                set;
            }
        }
        

        错误(CS0201):

        只有赋值、调用、递增、递减、等待和新对象表达式可以用作语句

        发生是因为get 方法中的语句txtName.Text; 实际上并没有做任何事情。 C 和 C++ 中的类似语句是合法的,但可能会触发编译器警告,例如“语句无效”。 C# 通过强制禁止这些语句的语法限制来防止这种编程错误。

        【讨论】:

          猜你喜欢
          • 2013-07-23
          • 2016-02-07
          • 2021-01-14
          • 1970-01-01
          • 2016-10-01
          • 2019-08-30
          • 2018-11-13
          • 2013-09-13
          相关资源
          最近更新 更多