簡體   English   中英

如何按名稱將現有表單動態添加到集合中

[英]How do I dynamically add an existing form to a collection by its name

我正在嘗試將一些現有表單動態添加到集合中。

下面的代碼將遍歷程序集並找到任何形式(希望我做對了)。 如果表單與表單名稱的一部分匹配,我想將其添加到集合中。 當然,我可以通過 Forms.add(new frm_Form1) 在代碼中明確地做到這一點。 我想這樣做,所以我不會忘記添加一個表單(我想我有點懶惰)。

    List<Form> Forms = new List<Form>();

    private void addForms()
    {
        Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

        foreach (Assembly a in assemblies)
        {
            Type[] types = a.GetTypes();

            foreach (Type t in types)
            {
                if (t.BaseType == typeof(Form))
                {
                    if (t.Name.Substring(0, 4).ToLower() == "frm_")
                    {
                        // How to add the form (found in the for loop) to the Forms collection.
                    }
                }
            }
        }
    }

希望你能幫忙。

謝謝

在您的循環中,您正在尋找類型 - 而不是實例。 當您找到一個並且這是您的目標時,您可以使用Activator.CreateInstance()創建您類型的實例,然后將其添加到您的集合中。 是 Activator 用法的示例。

Form instance = (Form)Activator.CreateInstance(t);
Forms.Add(instance);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM