类型 'System.Windows.Forms.Form' 没有 属性 命名为 'textBox1'

The type 'System.Windows.Forms.Form' has no property named 'textBox1'

正如人们在评论中指出的那样,你永远不应该为真正的应用程序这样做,因为这是不好的做法。我只是想了解属性实际上是如何与 Visual Studio 一起工作的,并且永远不会在真实的应用程序中这样做。

每当我尝试查看我创建的表单的设计时,都会收到此错误。我进入代码并将 textBox1 字段设置为 public 并添加了 getter 和 setter:

namespace WindowsFormsApplication2
{
    partial class Form2
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(85, 82);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(100, 20);
            this.textBox1.TabIndex = 0;
            // 
            // Form2
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Controls.Add(this.textBox1);
            this.Name = "Form2";
            this.Text = "Form2";
            this.ResumeLayout(false);
            this.PerformLayout();
        }

        #endregion
        public System.Windows.Forms.TextBox textBox1 { get; private set; }
    }
}

当我 运行 程序时,它编译并且 运行s 没有错误,并且显然有一个 textBox1 属性 声明。当我使用属性而不是普通字段时,为什么 Visual Studio 中断?

编辑:感谢您修复代码块,我自己正要这样做

您收到此错误是因为您手动更改了设计器生成的代码。 如果你在你的设计器中点击文本框,你可以通过设计器本身来public,然后你就不会遇到这个问题了。