Does a TextChanged event fire if the text hasn't changed?
I'm working on customizing (and fixing) a large application for a client which was purchased from another source. The code we ended up getting was most certainly NOT the actual code used in production by the source client. That being said, I ran into this today:
if (lblCurrentValueOfContractAmount.Text == "0.0")
lblCurrentValueOfContractAmount.Text = "0.0";
And no, I'm not joking. My first inclination was to just remove it, then I started talking to another developer who mentioned that there might be some clandestine stuff going on here, like somebody subscribed to the label's text being changed, etc. Honestly I'm not that concerned about it, so I'm just going to leave it in. However, this brings me to my question:
Let's assume that there is someone subscribed to TextChanged
, for example. If the text doesn't actually change, would the compiler optimize that whole statement away? Would the event actually fire?
Assuming you have a Winforms Label (or other Control derived class), the code will not fire a change event and therefore that code has no side effects and can be removed. http://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/Control.cs,9884211b7ff61817
public virtual string Text {
get { ... }
set {
if (value == null) {
value = "";
}
if (value == Text) {
return;
}
// omitted remainder
}
}
The compiler wouldn't optimize it away unless it could be proven to have no side-effects. Whether it has side-effects is a matter of exactly what the Text
property setter method does. What that setter does is up to the writer of that method. Good behavior would be to check whether the text has actually changed and only fire the TextChanged
event if a real change has occurred. But you can't just trust the original developer--time to do some testing of your own. Hook the TextChanged
event and see if it fires when you set, but don't actually change, the text.
The event will not fire over and over.
private void textBox1_TextChanged(object sender, EventArgs e)
{
// This does not cause the event to continuously fire
textBox1.Text = textBox1.Text;
}
I set the textbox initially to have the value "0.0" and then did this:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "0.0";
}
This did not cause the TextChangedEvent to fire.
链接地址: http://www.djcxy.com/p/25758.html上一篇: 方法与def