C#泛型功能

Dot*_*ude 13 c# generics

有人可以在泛型中解释这种行为吗?

我在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";
  }
}
Run Code Online (Sandbox Code Playgroud)

另外,当我在进行"Control is TextBox"类型的检查时,我可以使用switch case吗?

编辑:

忘了添加错误信息抱歉!

干得好:

Error   3   Cannot convert type 'T' to 'TextBox'
Run Code Online (Sandbox Code Playgroud)

编辑:

虽然我们在谈论泛型,但我有另一个问题.(不确定我是否必须开始新帖)

该方法已扩展为包括另一种泛型类型

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;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 21

泛型类型可以转换为什么的规则非常棘手,偶尔也会违反直觉,就像在这种情况下一样.有关详细信息,请参阅C#规范的6.2.6节.有些地方可能会有些松懈,我认为这是其中之一.你可以object再次施放然后再下降,但这很难看.

在这种情况下,更好的解决方案是:

protected virtual void LoadFieldDataEditor <T> (ref T control,
                                                string strFieldName) 
    where T : Control
{
    TextBox textBox = control as TextBox;
    if (textBox != null)
    {
        textBox.Text = "test";
    }
}
Run Code Online (Sandbox Code Playgroud)

除此之外,这只需要一次执行时间检查而不是两次.

对于旁注:不,您不能在类型上使用开关/案例.(你可以获得类型名称并打开它,但它会很糟糕.)