Может ли кто-нибудь объяснить это поведение в Generics?
У меня есть общая функция в С#
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";
}
}
На стороне примечания, могу ли я использовать случай переключения, когда я выполняю проверку типа "Control - TextBox"?
EDIT:
Забыл добавить сообщение об ошибке Извините!
Здесь вы идете:
Error 3 Cannot convert type 'T' to 'TextBox'
EDIT:
Пока мы говорим о дженериках, у меня есть другой вопрос. (Не уверен, если бы мне пришлось начать новую запись)
Этот метод был расширен, чтобы включить другой общий тип
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;
}