列出组件(不是控件)
本文关键字:控件 组件 | 更新日期: 2023-09-27 18:32:52
下面显示的代码显示了表单的所有可视和非可视组件(OpenDialogs,SaveDialogs等)。我希望我可以指定组件名称(无控件),而不是知道所有表单元素,如下所示:
private IEnumerable <Component> EnumerateComponents ()
{
return this.GetType () GetFields (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where (F => typeof (Component) .IsAssignableFrom (f.FieldType))
.Where (F => typeof (Control) .IsAssignableFrom (f.FieldType))
//.Where componentName.thatIinformed == "OpenDialog1" <<<<<======
.Select (F => f.GetValue (this))
.OfType <Component> ();
}
可能吗?
看起来你想要更多类似的东西:
public IEnumerable<Component> EnumerateComponents()
{
return this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(x => typeof(Component).IsAssignableFrom(x.PropertyType))
.Select(x => x.GetValue(this)).Cast<Component>();
}
我使用以下自定义UserControl
尝试了此操作:
public sealed class MyCustomControl : UserControl
{
// Adding some Controls for testing
public Label MyLabel1 { get; set; }
public Label MyLabel2 { get; set; }
// Adding a Component (not a Control) for testing
public System.Windows.Forms.Timer MyTimer1 { get; set; }
public IEnumerable<Component> EnumerateComponents()
{
return this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(x => typeof(Component).IsAssignableFrom(x.PropertyType))
.Select(x => x.GetValue(this)).Cast<Component>();
}
public IEnumerable<PropertyInfo> EnumerateProperties()
{
return this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(x => typeof(Component).IsAssignableFrom(x.PropertyType));
}
}
EnumerateProperties
方法只是为了让我可以测试它是否正在拾取我想要的属性。它包括我添加的 2 个Label
属性以及我包含的 Timer
属性(因为它不是Control
,只是一个Component
)。它还从符合标准的UserControl
继承了另外6个属性:ActiveControl
、ParentForm
、ContextMenu
、ContextMenuStrip
、Parent
和TopLevelControl
。
现在,获取其中每个值的值可能会返回大量null
值,因此您可能还需要过滤掉非 null 值。使用 OfType
而不是 Cast
还具有删除 null 值的副作用。