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

静态对象解除及关联事件的问题
C# code


public class Employee : System.ComponentModel.INotifyPropertyChanged
{
    private string _name;
    public string Name
    {
        get{return _name;}
        set{if(_name != value){
        _name =value;
        SendPropertyChanged("Name:"+value);
        }}
    }
    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
        protected virtual void SendPropertyChanged(String propertyName)
        {
            if ((this.PropertyChanged != null))
            {
                this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
}

public class ClassTest
{    
    public ClassTest()
    {       
       Gloal.Em.PropertyChanged -= Employee_PropertyChanged;    
       Gloal.Em.PropertyChanged += Employee_PropertyChanged;
    }
    private void Employee_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        Console.WriteLine(e.PropertyName);
    }
}

public class Gloal
{
   public static Employee Em;
}

static class Program
{
   [STAThread]
   static void Main(string[] args)
   {
    Gloal.Em = new Employee{Name = "a"};

    ClassTest t = new ClassTest();
    Gloal.Em.Name = "b";
    
    ClassTest t1 = new ClassTest();
    Gloal.Em.Name = "c";
    
    ClassTest t2 = new ClassTest();
    ClassTest t12 = new ClassTest();
    Gloal.Em.Name = "d";
   }
}



输出结果:
Name:b
Name:c
Name:c
Name:d
Name:d
Name:d
Name:d

-= 为啥不起作用呢?

------解决方案--------------------
C# code

public ClassTest()
    {       
       Gloal.Em.PropertyChanged -= Employee_PropertyChanged;    
       Gloal.Em.PropertyChanged += Employee_PropertyChanged;
    }
    private void Employee_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        Console.WriteLine(e.PropertyName);
    }