How to use base class & child class as parameter in one function ?
Steven Schveighoffer
schveiguy at gmail.com
Fri May 22 16:12:12 UTC 2020
On 5/22/20 9:10 AM, Vinod K Chandran wrote:
> On Friday, 22 May 2020 at 12:21:25 UTC, rikki cattermole wrote:
>> if (Child child = cast(Child)parent) {
>> assert(child !is null);
>> }
>
> Actually, problem occurs in addHandler function. It expects an argument
> of type "EventArgs", not MouseEventArgs.
Yes, because what if you did this with your function:
fnp(new EventArgs(...));
It would be called with the type being implicitly cast to the child type
without that being true.
What Rikki was recommending is that you write your handler like this:
void onClick(EventArgs e){
if(auto me = cast(MouseEventArgs)e) {
log("form clicked on x = ", me.x, ", and y = ", me.y);
}
}
Actually, if you are certain it's a programming error for onClick to be
called with a different type of event args, I'd do:
void onClick(EventArgs e){
auto me = cast(MouseEventArgs)e;
assert(me !is null, "Error, onClick called with invalid event type");
log("form clicked on x = ", me.x, ", and y = ", me.y);
}
More information about the Digitalmars-d-learn
mailing list