C# 向接受控件集合的方法发送下拉集合时出错
我试图将下拉控件的集合作为参数传递给一个方法,该方法将控件类型的集合作为输入。执行时,我得到以下错误: “无法将类型为“d_uA3C# 向接受控件集合的方法发送下拉集合时出错,c#,asp.net,linq,generics,extension-methods,C#,Asp.net,Linq,Generics,Extension Methods,我试图将下拉控件的集合作为参数传递给一个方法,该方法将控件类型的集合作为输入。执行时,我得到以下错误: “无法将类型为“d_uA31[System.Web.UI.WebControl.DropDownList]”的对象强制转换为类型为“System.Collections.Generic.IEnumerable1[System.Web.UI.Control]”。” 知道我为什么会得到这个吗 我的代码: private void Caller() { IEnumerable<DropD
1[System.Web.UI.WebControl.DropDownList]”的对象强制转换为类型为“System.Collections.Generic.IEnumerable
1[System.Web.UI.Control]”。”
知道我为什么会得到这个吗
我的代码:
private void Caller()
{
IEnumerable<DropDownList> dropDownControlsInCurrentRow = currentRow.Controls.OfType<DropDownList>();
SetControlsVisibility(dropDownControlsInCurrentRow, false);
}
private void SetControlsVisibility(IEnumerable<Control> controlCollection, bool visibilityFlag)
{
foreach (ctrl in controlCollection) {
ctrl.Visible = visibilityFlag;
}
}
private void Caller()
{
IEnumerable dropDownControlsInCurrentRow=currentRow.Controls.OfType();
SetControlsVisibility(dropDownControlsInCurrentRow,false);
}
私有void SetControlsVisibility(IEnumerable controlCollection,bool visibilityFlag)
{
foreach(controlCollection中的ctrl键){
ctrl.Visible=visibilityFlag;
}
}
在C#4.0中,由于IEnumerable中T的逆变,上述代码可以工作
在C#3.5及以下版本中,您需要添加额外的dropDownControlsInCurrentRow.Cast()
有关更多信息,请参见此链接
IEnumerable<Control> dropDownControlsInCurrentRow;
IEnumerable dropDownControlsInCurrentRow;
而不是
IEnumerable<DropDownList> dropDownControlsInCurrentRow;
IEnumerable dropDownControlsInCurrentRow;
类型的方法是您的还是框架的?如果它是你的,你能把代码写出来吗?如果它来自框架,那么currentRow
的类型是什么?^^^它是IEnumerable扩展方法(内置)。currentRow是GridViewRow类型。^^我接受这个答案,因为它为我提供了快速、必要的解决方案。