日期:2014-05-18  浏览次数:20956 次

若字符串内容改变则触发一个事件
我想在程序中实现若某一特定的字符串内容发生改变则触发某个事件应该怎样做?

------解决方案--------------------


private string strName ="";
public string Name
{
set
{
if(value !=strName)
{
//触发的事件;
strName =value;
}
}
}
------解决方案--------------------
C# code

        static void Main(string[] args)
        {
            Custom c = new Custom();
            c.ch += new Changed(delegate() { Console.WriteLine("Changed"); });
            c.Str = "123";
            c.Str = "234";
            c.Str = "234";
            #endregion

        }

        delegate void Changed();
        class Custom
        {
            public event Changed ch;
            private string str;
            public string Str
            {
                get { return str; }
                set
                {
                    if (str != value)
                    {
                        if (ch != null)
                            ch();
                    }
                    str = value;
                }
            }
        }