我如何隐式委托转换?

时间:2010-02-22 12:19:11

标签: .net event-handling

如何将委托隐式转换为其他委托?

// old
public delegate OldClickEventHandler(object sender, OldClickEventArgs e);
class OldClickEventArgs
{
 public int intEnumValue;
 OldClickEventArgs(int enumValue){ this.intEnumValue = enumValue; }
}

// new
public delegate NewClickEventHandler(object sender, NewClickEventArgs e);
class NewClickEventArgs
{
 public MyEnum EnumValue;
 NewClickEventArgs(MyEnum enumValue){ this.EnumValue = enumValue;  }

 public static implicit operator NewClickEventArgs(OldClickEventArgs e) {
  return new NewClickEventArgs((MyEnum)e.intEnumValue);
 }
}

// class NewButton : OldButton
// here I need to implicitly convert EventHandlers. HOW?
//
public event NewClickEventHandler Click
{
    add {
        oldObject.Click +=  value; // cannot convert New.. to Old..
    }
    remove {
        oldObject.Click -=  value; // cannot convert New.. to Old..
    }
 }

2 个答案:

答案 0 :(得分:3)

为了分配事件处理程序,他们必须具有相同的签名。在您的情况下,如果您的NewEventArgs扩展OldEventArgs,您可以实现此目的。 E.g。

class OldEventArgs : EventArgs
{
  // ... implementation ..
}

class NewEventArgs : OldEventArgs
{
  // ... implementation ...
}

在此之后,您应该能够将NewEventHandler分配给旧事件。

答案 1 :(得分:1)

我想你不能,除非你想让NewEventArgs继承OldEventArgs,但也许这种方法可以做到这一点

编辑:以前的课程一团糟(并没有奏效)。这些应该: - )

private Converter c = new Converter();

// when you want to trigger oldevent, call c.fireOld(sender, args);

public event OldEventHandler OldEvent {
    add { c.oldH += value; }
    remove { c.oldH -= value; }
}

public event NewEventHandler New {
    add { c.newH += value; }
    remove { c.newH -= value; }
}

public class Converter {
    public event OldEventHandler oldH;
    public event NewEventHandler newH;

    // call both old and new
    public void fireOld(object o, OldEventArgs args) {
        oldH(o, args);
        newH(o, args);
    }
}