开发者

How do I Implicit delegates conversion?

How do I implicitly convert a delegate to other?

// old
public delegate OldClickEventHandler(obj开发者_运维百科ect 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..
    }
 }


In order to assign the eventhandler they have to have the same signature. In you case you can achieve this if your NewEventArgs extends OldEventArgs. E.g.

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

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

After this you should be able to assign the NewEventHandler to the old event.


I guess you can't unless you want NewEventArgs to inherit from OldEventArgs, but perhaps this approach can do the trick

edit: the previous classes were a mess (and didn't work). These should :-)

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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜