【问题标题】:Error while sending a dropdown collection to a method accepting collection of Controls将下拉集合发送到接受控件集合的方法时出错
【发布时间】:2010-11-26 08:42:59
【问题描述】:

我正在尝试将 Dropdown 控件的集合作为参数传递给将 Control 类型的集合作为输入的方法。执行时出现以下错误:

“无法转换类型为 'd__a31[System.Web.UI.WebControls.DropDownList]' to type 'System.Collections.Generic.IEnumerable1[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;
   }
}

【问题讨论】:

  • OfType 方法是你的还是框架的?如果是你的,你能把代码放上来吗?如果来自框架,currentRow的类型是什么?
  • ^^ 它是 IEnumerable 扩展方法(内置)。 currentRow 是 GridViewRow 类型的。

标签: c# asp.net linq generics extension-methods


【解决方案1】:

使用

IEnumerable<Control> dropDownControlsInCurrentRow;

而不是

IEnumerable<DropDownList> dropDownControlsInCurrentRow;

【讨论】:

  • ^^ 我接受了这个作为答案,因为它给了我快速、需要的解决方案。
【解决方案2】:

在 C# 4.0 中,由于 IEnumerable 中 T 的逆变性,上述代码可以正常工作。

在 C# 3.5 及以下版本中,您需要添加一个额外的 dropDownControlsInCurrentRow.Cast()

查看此链接on contravariance了解更多信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    相关资源
    最近更新 更多