如何找到实现接口并调用方法的所有对象

本文关键字:方法 对象 调用 何找 实现 接口 | 更新日期: 2023-09-27 18:07:04

我有一个UserControl,有几个孩子UserControl 's和那些UserControl 's有孩子UserControl's。

考虑一下:

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);
    }
}

是否有可能从MainUserControl中找到所有通过反射实现ISomeInterface并在该接口上调用方法(void SomeMethod())的子UserControl 's ?

如何找到实现接口并调用方法的所有对象

您需要递归地遍历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();

这似乎是最好的。:)

也许我自己看错方向了。我评论马修斯的回答的意思是:

 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();
     }
 }