【问题标题】:ASP.net Cast FindControl output to a parameterASP.net 将 FindControl 输出转换为参数
【发布时间】:2016-03-16 08:25:41
【问题描述】:

我想将 FindControl 方法的输出转换为特定类型的控件,但我希望将类型本身作为参数传递。我第一次尝试:

public static List<T> GetList<T>(..., Type tp, ...)
{
...
tp castedCtrl = (panel.FindControl(ctrlPrefixName + i.ToString()) as tp);
...
}

这是我的首选结果,但根本无法编译。 我也试过了:

dynamic castedCtrl = Convert.ChangeType(panel.FindControl(ctrlPrefixName + i.ToString()), tp);

但这需要我所有的 tp 实现 IConvertible 接口,这是不希望的,并且需要很多意想不到的工作。

如何将 FindControl 输出的输出转换为我想要的类型(实际上我想传递用户控件类的名称)。

【问题讨论】:

  • 类型是否经常更改,您每次都想将其作为参数传递?

标签: asp.net casting webforms findcontrol dynamic-controls


【解决方案1】:

给你:

public static List<T> GetList<T, U>(Page page, string ctrlPrefixName) 
   where T : class 
   where U : Control
{
   int i = 1;
   U castedCtrl = page.FindControl(ctrlPrefixName + i.ToString()) as U;
   return new List<T>();
}

为了使用它:

GetList<MyType, DropDownList>(this, "MyControl_");

【讨论】:

  • 请考虑 T 是一个单独的类
  • 我代码中的T实际上代表了ascx的数据对象
  • 所以你可以写 where T : class 然后你可以使用任何你想要的类。但是,如果您要寻找控件,则无论如何您的类都需要从 Control 类继承。
  • 我想在参数之间传递类型,T 用于不同的目的(将该控件的信息打包到一个对象中)
  • 你不能使用类型作为变量,但是你可以在方法声明中添加第二个泛型类型。
猜你喜欢
  • 2018-12-24
  • 1970-01-01
  • 2021-09-05
  • 2015-04-02
  • 1970-01-01
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
  • 2020-04-29
相关资源
最近更新 更多