¿Alguien puede explicar este comportamiento en Generics?C# Generics function
que tienen una función genérica en C#
protected virtual void LoadFieldDataEditor <T> (ref T control, string strFieldName) where T : Control
{
//T can be different types of controls inheriting from System.Web.UI.Control
if (control is TextBox)
{
//This line gives an error
//((TextBox)control).Text = "test";
//This line works!
(control as TextBox).Text = "Test";
}
}
En una nota lateral, puedo usar el caso del interruptor cuando estoy haciendo un "control de cuadro de texto es" tipo de cheques?
EDIT:
olvidó añadir el mensaje de error Lo sentimos!
Aquí van:
Error 3 Cannot convert type 'T' to 'TextBox'
EDIT:
Si bien estamos hablando de los genéricos, tengo otra pregunta. (No estaba seguro si tuviera que empezar una nueva entrada)
El método se ha ampliado para incluir otro tipo genérico
protected virtual void LoadFieldDataEditor <T1, T2> (T1 control, T2 objData, string strFieldName) where T1 : Control where T2 : BaseDataType
{
//I will need to access field1.
//I don't know at compile time if this would be SomeType1 or
//SomeType2 but all of them inherit from BaseDataType.
//Is this possible using generics?
}
public abstract class BaseDataType {}
public class SomeType1 : BaseDataType
{
string field1;
string field2;
}
Cuando pregunta qué significa un error, es realmente útil decir cuál es el error. Solo estoy tratando de reproducir ahora ... –
¿Cuál es el error? –
@Jon Skeet: Maldita sea ... No me di cuenta de que estabas en la caja ... –