有人可以解释泛型中的这种行为吗?
我在 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";
}
}
附带说明一下,当我进行“Control is TextBox”类型的检查时,我可以使用 switch case 吗?
编辑:
忘记添加错误信息抱歉!
给你:
Error 3 Cannot convert type 'T' to 'TextBox'
编辑:
当我们在谈论泛型时,我有另一个问题。 (不确定我是否必须开始一个新帖子)
该方法已扩展为包含另一个泛型类型
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;
}
最佳答案
关于泛型类型可以转换成什么的规则非常棘手,有时甚至违反直觉,就像在本例中一样。有关详细信息,请参阅 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";
}
}
除此之外,这只需要一次执行时间检查,而不是两次。
旁注:不,您不能在类型上使用 switch/case。 (您可以获得类型名称并打开它,但这会很糟糕。)
关于C# 泛型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/642933/