关于C#中”扩展方法必须在非泛型静态类中定义“问题的解决

问题描述:this

       在某个窗口下的编码中使用了如下扩展方法FindControl,以求根据字符串的值去操做控件(本文中的控件为Label控件)的属性。编码

     public static Control FindControl(this Control parentControl, string findCtrlName)orm

        {字符串

            Control _findedControl = null;string

            if (!string.IsNullOrEmpty(findCtrlName) && parentControl != null)io

            {泛型

                foreach (Control ctrl in parentControl.Controls)扩展

                {foreach

                    if (ctrl.Name.Equals(findCtrlName))引用

                    {

                        _findedControl = ctrl;

                        break;

                    }

                }

            }

            return _findedControl;

        }

       使用后错误列表中显示错误,错误描述为”扩展方法必须在非泛型静态类中定义“,错误的指示下划线指到了代码段中的Form2处。

 

解决方案:

      在相同的名称空间下新建了一个静态类,类名为ExtensionClass,而后把扩展方法代码移至该类中。以下图:

 

      而后在Form2的代码块中经过引用该方法,实现了目的,以下图:

相关文章
相关标签/搜索