110,580
社区成员
发帖
与我相关
我的任务
分享
private void InitializeComponent()
{
this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
this.SuspendLayout();
//
// numericUpDown1
//
this.numericUpDown1.Location = new System.Drawing.Point(0, 0);
this.numericUpDown1.Name = "numericUpDown1";
this.numericUpDown1.Size = new System.Drawing.Size(120, 22);
this.numericUpDown1.TabIndex = 0;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(282, 255);
this.Controls.Add(this.numericUpDown1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
this.ResumeLayout(false);
}
My m = new My();
m.Max = 20;
m.BeginInit();
m.Current = 3;
m.Current = 4;
m.EndInit();
发现,果然BeginInit期间,这个Initializing是true,也就是if括号当中的语句不会执行。
非常感谢你的解释!
class My : Component, ISupportInitialize
{
private bool Initializing { get; set; }
public int Max { get; set; }
private int current;
public int Current
{
get { return current; }
set
{
if (current > Max && !Initializing)
{
throw new InvalidOperationException("too big");
}
current = value;
}
}
public void BeginInit()
{
Initializing = true;
}
public void EndInit()
{
if (this.Current > this.Max) throw new Exception("...");
Initializing = false;
}
}