2009-05-27 67 views
2

我正在使用System.Reflection加载一个我在设计时无法加载的类型。我需要将这个类型的集合中的所有控件都拉出来,但是,OfType命令似乎不喜欢反射语法。这里是“接近”我得到的。.Net使用反射来定义OfType

Dim ControlType As Type = System.Reflection.Assembly.GetAssembly(_ 
          GetType(MyAssembly.MyControl)) _ 
         .GetType("MyAssembly.MyUnexposedControl") 

Dim Matches as List(Of Control) = MyBaseControl.Controls.OfType(Of ControlType) 

因此,代码是假的,它不起作用,但你知道我正在尝试做什么。那么有没有一种方法可以使用反射并获得所有这种类型的控件?

回答

3

OfType是一种通用方法,因此您可以给它一个静态类型(例如OfType(Of String)),而不是在运行时确定的System.Type。

你可以这样做:

Dim CustomControlType as Type = LoadCustomType() 

MyBaseControl.Controls.Cast(Of Control)().Where(Function(ctrl) ctrl.GetType().IsAssignableFrom(CustomControlType)) 

使用Cast(Of Control)ControlCollectionIEnumerable)转换为IEnumerable<Control>,然后得到所有的拉姆达扩展。

+0

这个好,但是,“去哪儿”,似乎看不出现在System.Web.UI.ControlCollection – 2009-05-27 22:17:17

0

尝试这样的:

Dim ControlType As Type = System.Reflection.Assembly.GetAssembly(_ 
         GetType(MyAssembly.MyControl)) _ 
        .GetType("MyAssembly.MyUnexposedControl") 

Dim Matches as List(Of Control) = MyBaseControl.Controls.Where(Function(control) ControlType.GetType().IsAssignableFrom(control.GetType()) 
0

为什么不与你测试类型在哪里更换OfType?

Dim Matches as List(Of Control) = MyBaseControl.Controls.Where(Function(ctl) ctl.GetType() = ControlType) 

编辑:达林是更快......实际上他的解决方案是更好,因为它处理派生类

0

您是否尝试过这样的事情?

Dim query = From i In MyBaseControl.Controls Where i.GetType is ControlType