1

我项目中的许多表单都继承自基本表单。很容易获得派生表单的 Controls 集合,但我还没有找到访问 Components 集合的简单方法,因为 VS 将其标记为私有。

我认为这可以通过反射来完成,但我不确定如何最好地去做,因为之前没有使用过反射。

现在,我正在使用一种笨拙的解决方法,其中我覆盖了一个函数 GetComponents 并返回一个我感兴趣的组件数组。这显然容易出错,因为很容易忘记实现被覆盖的函数或在添加组件时更新它。

如果有人有任何提示或可以提出更好的方法,我会很高兴听到。

4

3 回答 3

1

如果将组件的 Modifiers 属性设置为严格保护,则无需使用组件集合即可访问它们。

编辑:可发现性可以使用反射来遍历每个字段。尽管在您的情况下这可能不是最理想的。

于 2008-08-27T20:37:28.857 回答
0

Set the 'components' modifier to protected in your base form class. Remove the 'components' declaration in all the derived forms.

Call this below method in base form load event,

        public void SetComponentsStyle()
    {
        if (null != this.components)
        {
            foreach (Component comp in this.components.Components)
            {
                if (comp is ToolTip)
                {

                }
                else if (comp is ContextMenuStrip)
                {

                }
            }
        }
    }
于 2013-06-09T08:43:00.547 回答
0

如果您担心忘记覆盖该函数,请将其抽象化。

于 2008-08-27T20:19:53.890 回答