Puis-je avoir une méthode renvoyant IEnumerator<T> et l'utiliser dans une boucle foreach ?

Je dois définir la hauteur de chaque zone de texte de mon formulaire, dont certaines sont imbriquées dans d'autres contrôles. Je pensais que je pouvais faire quelque chose comme ça :

private static IEnumerator<TextBox> FindTextBoxes(Control rootControl)
{
    foreach (Control control in rootControl.Controls)
    {
        if (control.Controls.Count > 0)
        {
            // Recursively search for any TextBoxes within each child control
            foreach (TextBox textBox in FindTextBoxes(control))
            {
                yield return textBox;
            }
        }

        TextBox textBox2 = control as TextBox;
        if (textBox2 != null)
        {
            yield return textBox2;
        }
    }
}

En l'utilisant comme ceci :

foreach(TextBox textBox in FindTextBoxes(this))
{
    textBox.Height = height;
}

Mais bien sûr, le compilateur crache son mannequin, car foreach attend un IEnumerable plutôt qu'un IEnumerator.

Existe-t-il un moyen de faire cela sans avoir à créer une classe séparée avec une méthode GetEnumerator() ?

请先 登录 后评论

4 réponses

David Wengier

Comme le compilateur vous l'indique, vous devez changer votre type de retour en IEnumerable. C'est ainsi que fonctionne la syntaxe de retour de rendement.

请先 登录 后评论
Yaakov Ellis
// Generic function that gets all child controls of a certain type, 
// returned in a List collection
private static List<T> GetChildTextBoxes<T>(Control ctrl) where T : Control{
    List<T> tbs = new List<T>();
    foreach (Control c in ctrl.Controls) {
        // If c is of type T, add it to the collection
        if (c is T) { 
            tbs.Add((T)c);
        }
    }
    return tbs;
}

private static void SetChildTextBoxesHeight(Control ctrl, int height) {
    foreach (TextBox t in GetChildTextBoxes<TextBox>(ctrl)) {
        t.Height = height;
    }
}
请先 登录 后评论
Joseph Daigle

Si vous renvoyez IEnumerator, ce sera un objet énumérateur différent à chaque appel de cette méthode (agissant comme si vous réinitialisiez l'énumérateur à chaque itération). Si vous renvoyez IEnumerable, un foreach peut énumérer en fonction de la méthode avec l'instruction yield.

请先 登录 后评论
Orion Edwards

Juste pour clarifier

private static IEnumerator<TextBox> FindTextBoxes(Control rootControl)

Modifications de

private static IEnumerable<TextBox> FindTextBoxes(Control rootControl)

Ça devrait être tout :-)

请先 登录 后评论
  • 10 abonnés
  • 0 favoris,475 Feuilleter
  • littlecharva posée à 2023-03-05 06:33