【发布时间】:2015-03-11 09:55:54
【问题描述】:
正如人们在 cmets 中指出的那样,您永远不应该为真正的应用程序这样做,因为这是不好的做法。我只是想了解属性在 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; }
}
}
当我运行程序时,它编译并运行没有错误,并且显然声明了一个 textBox1 属性。为什么我使用属性而不是普通字段时 Visual Studio 会中断?
编辑:感谢您修复代码块,我正要自己这样做
【问题讨论】:
-
与其用公共自动属性替换字段,不如添加一个属性来提供对设计器生成的字段的访问权限?
-
你真的不应该尝试更改designer.cs文件..使用部分类的另一半
-
@GrawCube,我认为使用自动属性比为每个组件使用单独的属性更简洁。从理论上讲,这应该有效。我只是想知道为什么它没有。
-
@Sayse 我知道,但这更像是一个实验。如果我正在编写一个实际的应用程序,我永远不会这样做。
标签: c# visual-studio-2013 properties windows-forms-designer