代码之家  ›  专栏  ›  技术社区  ›  Slavo

如何确保实际引发了来自接口的事件?

  •  1
  • Slavo  · 技术社区  · 15 年前

    关于接口中的事件有许多问题。以下是一些:

    由于接口用于强制实施契约,因此对我来说这没有意义,因为它不强制实际引发事件。特定的实现可以始终拥有事件,但不能在任何地方引发它。考虑以下内容:

    public interface INotifyPropertyChanged
    {
        event PropertyChangedEventHandler PropertyChanged;
    }
    
    public class SomeClass : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        public string SomeProperty
        {
            get { return this.someField; }
            set { this.someField = value; }
        }
    
        private string someField;
    }
    

    上面的内容将编译并工作,但是即使我订阅了PropertyChanged事件,也不会发生任何事情。什么是强制事件实际被引发的方法,如果不是,为什么首先在接口中有事件?

    7 回复  |  直到 15 年前
        1
  •  4
  •   Mitch Wheat    15 年前

        2
  •  4
  •   Thomas Weller    15 年前

        3
  •  3
  •   Chris Pitman    15 年前
        4
  •  2
  •   AakashM    15 年前

    PropertyChanged

        5
  •  1
  •   Paul Hadfield    15 年前

        6
  •  1
  •   Grant Crofton    15 年前
        7
  •  0
  •   BlackICE    15 年前

    INotifyPropertyChanged x = new SomeClass();
    x.PropertyChanged += MyHandler;  //you get the idea