c#如何控制哪个修饰符是私有的

时间:2017-06-09 09:50:41

标签: c#

我有一个private形式的自定义控件。

在另一种形式我有这样的代码

foreach(Form f in Application.OpenForms)

其中一种表格是Formthatcontaincontrols

Formthatcontaincontrols包含自定义控件private,我需要从"f"

格式访问该自定义控件

3 个答案:

答案 0 :(得分:2)

您可以通过公共财产公开控件:

Formthatcontaincontrols

public TheCustomControlYouWant TheCustomControl
{
    get { return this.CustomControl; }
}

然后您可以访问此属性:

foreach(Formthatcontaincontrols f in Application.OpenForms.OfType<Formthatcontaincontrols>())
{
    TheCustomControlYouWant ctrl = f.TheCustomControl;
}

答案 1 :(得分:1)

使用控件时请不要公开实现细节。

从您的父自定义控件(Formthatcontaincontrols)的使用者角度来看,应隐藏实现细节。

我假设您需要访问某些对Formthatcontaincontrols的消费者很重要的属性。

我建议公开这个属性,让控件本身找到相关的子节点并访问子控件中定义的内部属性。

您可以使用@Tim Schmelter粘贴的解决方案找到Formthatcontaincontrols

答案 2 :(得分:0)

您可以浏览表单中的所有控件:

private List<T> FindControls<T>(Control.ControlCollection controls) where T: Control
{
    List<T> list = new List<T>();
    foreach (Control control in controls)
    {
        var matched = control as T;
        if (matched != null)
            list.Add(matched);
        else
            list.AddRange(FindControls<T>(control.Controls));
    }
    return list;
}

例如,您可以使用以下方法搜索所有按钮:

foreach (var btn in FindControls<Button>(yourForm.Controls))
{
    Trace.WriteLine(btn.Name);
}