从当前命名空间获取用户定义的控件列表

Get a List of User-Defined Controls From Current Namespace

如何获得添加到当前命名空间的所有用户定义控件的列表? 我正在使用 C# 2010。

你可以使用反射。试试这个代码:

public static class ControlsFinder
{
    public static List<Type> FindControls(Assembly controlsLibrary,
        string rootNamespace, bool includeNestedTypes = true)
    {
        var parent = typeof(UserControl);
        return controlsLibrary.GetTypes()
            .Where(t => (includeNestedTypes 
                ? t.FullName.StartsWith(rootNamespace)
                : t.FullName.Equals($"{rootNamespace}.{t.Name}"))
                && parent.IsAssignableFrom(t))
            .ToList();
    }
}

用法示例:

var controls = ControlsFinder.FindControls(Assembly.GetExecutingAssembly(), "WinFrm");

如果您只想要名字,您可以 select 来自 controls:

var names = controls.Select(t => t.Name).ToArray();

使用这些方法,我可以提取项目中所有用户定义控件的列表,并根据表单上的名称创建用户定义控件的实例。

        var assemblies = AppDomain.CurrentDomain.GetAssemblies();           // Get my CurrentDomain Object
        Assembly myType = Assembly.GetExecutingAssembly();                  // Extract list of all references in my project
        foreach (var assembly in assemblies)                                // Search for the library that contains namespace that have needed controls
        {
            if (assembly.GetName().ToString().ToUpper().IndexOf("FIBACONTROLS") > -1)   
            {
                myType = assembly;                                          // Get All types in the library
                List<Type> myTps = myType.GetTypes().ToList();


                Type mT = null;
                foreach (Type selType in myTps)                             // Find the type that refer to needed user-defined control
                {
                    if (selType.Name.ToUpper() == "FIBACOLORPICKER")
                    {
                        mT = selType;
                        break;
                    }
                }

                if (mT == null)
                    return;

                object myInstance = Activator.CreateInstance(mT);           // Created an instance on the type
                Control mFib = (Control)myInstance;                         // create the control's object
                mFib.Name = "Hahah";                                        // add the control to my form
                mFib.Left = 100;
                mFib.Top = 200;
                mFib.Visible = true;

                this.Controls.Add(mFib);

                break;
            }
        }

我尝试在代码中添加一些注释来描述它。

它可以工作,并且肯定有一些更好的方法来做到这一点,但我是 C# 的新手,我确信我找到的解决方案不是最好的。