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

时间:2013-04-01 09:57:03

标签: c# .net wpf reflection interface

我有一个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())?

2 个答案:

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