반사를 사용하여 이벤트를 구독 할 수 있습니다.
정의 하위 클래스 :
class Child {
public Child() { }
// Define event
public event EventHandler DidSomethingNaughty;
// Proeprty used to trigger event
public bool IsNaughty {
get { return this.isNaughty; }
set {
this.isNaughty = value;
if (this.IsNaughty) {
if (this.DidSomethingNaughty != null) {
this.DidSomethingNaughty(this, new EventArgs());
}
}
}
}
// Private data member for property
private bool isNaughty = false;
}
정의 어머니 등급 :
class Mother {
public Mother() {
this.subscribeToChildEvent();
}
// Properties
public Child Child1 {
get { return this.child1; }
set { this.child1 = value; }
}
public Child Child2 {
get { return this.child1; }
set { this.child2 = value; }
}
public Child Child3 {
get { return this.child3; }
set { this.child3 = value; }
}
public Child Child4 {
get { return this.child4; }
set { this.child4 = value; }
}
// Private data members for the properties
private Child child1 = new Child();
private Child child2 = new Child();
private Child child3 = new Child();
private Child child4 = new Child();
// This uses reflection to get the properties find those of type child
// and subscribe to the DidSomethingNaughty event for each
private void subscribeToChildEvent() {
System.Reflection.PropertyInfo[] properties =
typeof(Mother).GetProperties();
foreach (System.Reflection.PropertyInfo pi in properties) {
if (pi.ToString().StartsWith("Child")) {
Child child = pi.GetValue(this, null) as Child;
child.DidSomethingNaughty +=
new EventHandler(child_DidSomethingNaughty);
}
}
}
private void child_DidSomethingNaughty(object sender, EventArgs e){
Child child = (Child)sender;
if (child.IsNaughty) {
this.discipline(child);
}
}
private void discipline(Child child) {
MessageBox.Show("Someone was naughty");
// reset the flag so the next time the childe is
//naughty the event will raise
child.IsNaughty = false;
}
}
는 그런 어머니 객체를 초기화하고이 사건에 첨자됩니다
Mother m = new Mother();
는 그 다음 IsNaughty 설정 Child1의 속성이 true 일 때 :
,
m.Child1.IsNaughty = true;
당신은 메시지 상자를 얻어야한다 :
자료 :
https://stackoverflow.com/a/737156/1967692
https://stackoverflow.com/a/3179869/1967692
는 "이 아이들의 모든 이벤트를 등록은 객체". 이 성명을 통해 관계가 어느 방향으로 향하는 지 명확하지 않습니다 (누가 파견자이며 누가 수령자인지). 왜 우리에게 보여줄 코드를 게시할까요? – spender
대리인의 멀티 캐스트 특성이 그렇게하지 않는다고 가정합니다. 게시자에게 많은 메소드를 등록 하시겠습니까? 그래서 어머니 클래스가이 델리게이트 나 이벤트를 공유한다면, 모든 아이들이 그것을 구독 할 수 있습니다. 아마도 그것을 올바르게 이해하지 못했을 것입니다. –
더 명확하게하십시오. 그것은 불분명하다. –