我有一个UserControl
有一些孩子UserControl
,那些UserControl
有子UserControl。
考虑一下:
MainUserControl
TabControl
TabItem
UserControl
UserControl
UserControl : ISomeInterface
TabItem
UserControl
UserControl
UserControl : ISomeInterface
TabItem
UserControl
UserControl
UserControl : ISomeInterface
TabItem
UserControl
UserControl
UserControl : ISomeInterface
这是我到目前为止,但没有找到ISomeInterface
:
PropertyInfo[] properties = MainUserControl.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
if (typeof(ISomeInterface).IsAssignableFrom(property.PropertyType))
{
property.GetType().InvokeMember("SomeMethod", BindingFlags.InvokeMethod, null, null, null);
}
}
是否有可能通过反射找到UserControl
中实现MainUserControl
的所有子ISomeInterface
并在该界面上调用方法(void SomeMethod()
)?
答案 0 :(得分:4)
您需要递归遍历MainUserControl中的所有子控件。
这是您可以使用的辅助方法:
/// <summary>
/// Recursively lists all controls under a specified parent control.
/// Child controls are listed before their parents.
/// </summary>
/// <param name="parent">The control for which all child controls are returned</param>
/// <returns>Returns a sequence of all controls on the control or any of its children.</returns>
public static IEnumerable<Control> AllControls(Control parent)
{
if (parent == null)
{
throw new ArgumentNullException("parent");
}
foreach (Control control in parent.Controls)
{
foreach (Control child in AllControls(control))
{
yield return child;
}
yield return control;
}
}
然后:
foreach (var control in AllControls(MainUserControl))
{
PropertyInfo[] properties = control.GetType().GetProperties();
... Your loop iterating over properties
或者(如果这对你有用,那就更好了,因为它更简单):
foreach (var control in AllControls(MainUserControl))
{
var someInterface = control as ISomeInterface;
if (someInterface != null)
{
someInterface.SomeMethod();
}
}
或者,使用Linq(需要using System.Linq
来执行此操作):
foreach (var control in AllControls(MainUserControl).OfType<ISomeInterface>())
control.SomeMethod();
这似乎是最好的。 :)
答案 1 :(得分:2)
也许我自己看错了方向。我对马修斯答案的评论意味着:
foreach (var control in AllControls(MainUserControl))
{
if (control is ISomeInterface)
{
}
}
或
foreach (var control in AllControls(MainUserControl))
{
var someInterface = control as ISomeInterface;
if (someInterface != null)
{
someInterface.SomeMethod();
}
}