1

我有一个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);
    }
}

是否有可能通过反射UserControlMainUserControl该实现中找到所有 child 并在该接口上ISomeInterface调用方法( )?void SomeMethod()

4

2 回答 2

5

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

这似乎是最好的。:)

于 2013-04-01T10:07:02.483 回答
3

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

 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();
     }
 }
于 2013-04-01T10:15:29.547 回答