我有一个改变颜色的类Shape,它应该在发生更改时通知订阅者。但是,订阅者希望收到如下通知:
green
,yellow
或red
时才会收到通知red
时才会收到通知这是我的Shape类
public class Shape
{
public event EventHandler ColorChanged;
void ChangeColor()
{
// set new color
OnColorChanged(...);
}
protected virtual void OnColorChanged(MyEventArgs e)
{
if(ColorChanged != null)
{
ColorChanged(this, e);
}
}
}
和我的订阅者
public class Subscriber1
{
public Subscriber1(Shape shape)
{
shape.ColorChanged += new EventHandler(OnColorChanged);
}
void OnColorChanged(object sender, EventArgs e)
{
// this subscriber wants to get notified only if color changes to green, yellow and red
}
}
public class Subscriber2
{
public Subscriber2(Shape shape)
{
shape.ColorChanged += new EventHandler(OnColorChanged);
}
void OnColorChanged(object sender, EventArgs e)
{
// this subscriber wants to get notified only if color changes to red
}
}
public class Subscriber3
{
public Subscriber3(Shape shape)
{
shape.ColorChanged += new EventHandler(OnColorChanged);
}
void OnColorChanged(object sender, EventArgs e)
{
// this subscriber wants to get notified every time shape color changes
}
}
如何让Shape通知这些订户在其首选条件下的颜色变化(即我希望仅在您的颜色变为红色时才收到通知)?
我看到的每个例子都会通知所有订阅者所有更改,我试图这样做
您必须为每个不同的可能订阅选项维护一个委托列表:
private Dictionary<Color, EventHandler> colorChangedHandlers;
private EventHandler color_changed_to_red;
private EventHandler color_changed_to_yellow;
.
.
.
// then, add all of the delegates to the list
订阅者必须打电话
shapeInstance.SubscribeColorChanged(EventHandler handler, params Color[] desiredColors);
然后,你必须实现它,像这样:
public void SubscribeColorChanged(EventHandler handler, params Color[] colors)
{
foreach (Color c in colors)
{
colorChangedHandlers[c] += handler;
}
}
当然,您还需要伴随的Unsubscribe
方法:
public void UnsubscribeColorChanged(EventHandler handler, params Color[] desiredColors)
{
foreach (Color c in desiredColors)
{
foreach (KeyValuePair<Color, EventHandler> kvp in colorChangedHandlers)
{
if (kvp.Key == c) {
EventHandler tmp = kvp.Value;
tmp -= handler;
}
}
}
}
然后,你将不得不改变你的OnColorChanged
方法
protected virtual void OnColorChanged(Color color)
{
colorChangedEventHandlers[color]?.Invoke(this, EventArgs.Empty);
}
所有这一切只是为了一个ColorChanged
事件,可以使用NewColor
派生类的EventArgs
属性处理!!另外,自定义颜色必须更复杂,因为这只涉及Colors
枚举中的值。这可能是可能的,但我不建议任何人没有明确和绝望的需要。