简体   繁体   中英

Can a switch statement be used on Control objects passed to an event handler?

I have multiple controls that share the same event handler. Instead of writing a series of

if(sender == specific_control)
{
     // do something
}

Is there a way I could use a switch statement or something similar instead?

When I type switch(sender) I get an error message that says

A switch expression or case label must be a bool, char, string, intergral, enum, or corresponding nullable type.

If you want the event handler to do something different depending on which control raised the event, why are you using the same handler for each control? Just give each control its own handler method.

If there is some common code to execute when handling all of the different events, put that into a single method that can be called by the various event handler methods.

If the above advice does not seem applicable to your scenario, please improve your question so that it's clear why it's not. Be sure to include a good, minimal , complete code example that clearly illustrates the explanation.

If these controls are of the same types, then you can use the "Type" of the control to generate a switch statement:

//Just a snippet, you can use the FullName or Name to determine which
//control it belongs to...
        Type t = (sender).GetType();
        switch (t.FullName)
        {
            case "Namespace.Control1":
                break;
            case "Namespace.Control2":
                break;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM