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

问题描述:

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

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

        {

            Control _findedControl = null;

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

            {

                foreach (Control ctrl in parentControl.Controls)

                {

                    if (ctrl.Name.Equals(findCtrlName))

                    {

                        _findedControl = ctrl;

                        break;

                    }

                }

            }

            return _findedControl;

        }

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

解决方案:

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

 

      然后在Form2的代码块中通过引用该方法,实现了目的,如下图:

原文地址:https://www.cnblogs.com/xinweichen/p/6594262.html