简体   繁体   中英

Can I add an EventHandler to a String?

I was just wondering if I could "trigger" something when the value of a variable (like int , string etc.) changes?

Suppose I have a TextBox tb which shows the value of String MyString . So what I want to do is something like this:

MyString.ValueChanged += new EventHandler(UpdateTextBox);

public void UpdateTextBox(object sender, EventArgs e)
{
tb.Text = MyString;
}

In order to not have to update the textbox in multiple lines. Is there any way to do this? Thanks !

A string never changes . It is immutable (barring evil code that works under the hood). If MyString is a property , then you could of course have a MyStringChanged event, and hook that up to the event handler.

private string myString;
public string MyString {
    get { return myString; }
    set {
       if(myString != value) {
          myString = value;
          var handler = MyStringChanged;
          if(handler!=null) handler(this,EventArgs.Empty);
       }
    }
}
public event EventHandler MyStringChanged;

Values such as int and string are immutable. They can't change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM