Pregunta

C# .net , winforms application., Visual studio 2010

I have created a control c which can be Textbox or combobox. now i want to type cast c dynamically that if sender is combobox than typecast c with combobox, if sender is textbox make c as textbox.

Here is the sample code for performing this, but i am looking for better way.

If you have pls suggest..

Now i am doing in this way

private void Test(Object sender, EventArgs e)
{
  Control c = sender as Textbox(); //assuming sender is textbox
  if( c== null)
 {
   c = sender as ComboBox(); // assuming sender is combobox
 }
}

 // I want better way.

for example

c = sender as Combobox() || sender as Textbox //Like this
¿Fue útil?

Solución

Your code assigns the cast to a Control object, so you actually don't need the cast at all. You could just write:

Control c = sender as Control;

This works because ComboBox and TextBox both derive from Control, and you can always upcast ("up" refers to the direction of inheritance).

This works great if all you care about are the properties TextBox and ComboBox inherit from Control. If you need properties specific to those types, you need to do the cast, and assign to the appropriate type:

TextBox b = sender as TextBox;
if (b != null)
{
   //Do stuff with it as a TextBox
}
else
{
    ComboBox c = sender as ComboBox;

    //You should still perform the check here as a matter of good practice.
    if (c != null)
    {
        //Do stuff with it as a ComboBox
    }
}

Otros consejos

You can use the dynamic type:

private void Test(Object sender, EventArgs e)
{
  dynamic box = sender;
  box.DoStuff(); //will throw a run-time exception if DoStuff() doesn't exist 
} 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top