C# 文字列から Type 型へ - 任意のオブジェクトを柔軟に作成

        //思路:
        //使用Assembly中的GetType()方法可以按字符串名称查找指定程序集中的类型。
        //可以获取当前程序中所有加载的程序集,遍历找到对应的Type
        //使用AppDomain.CurrentDomain.GetAssemblies()获取默认运行程序域中的所有程序集
  
        //实现:
        public static Type GetTypeByName(string fullName)
        {
            //获取应用程序用到的所有程序集
            var asy = AppDomain.CurrentDomain.GetAssemblies();
            for (int i = 0; i < asy.Length; i++)
            {
                //从对应的程序集中根据名字字符串找的对应的实体类型
                //需要填写包括命名空间的类型全名,例"System.Windows.Forms.Button"
                if (asy[i].GetType(fullName, false) != null)
                {
                    return asy[i].GetType(fullName, false);
                }
            }
            return null;
        }

ケース: 任意のコントロールを動的に生成し、ウィンドウに追加する

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DynamicGenerate
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
  
        private void button1_Click(object sender, EventArgs e)
        {
            Type tp = null;
            switch (comboBox1.Text)
            {
                case "TextBox":
                    tp = GetTypeByName("System.Windows.Forms.TextBox");
                    break;
                case "Button":
                    tp = GetTypeByName("System.Windows.Forms.Button");
                    break;
                case "Label":
                    tp = GetTypeByName("System.Windows.Forms.Label");
                    break;
                default:
                    break;
            }
            if (tp!=null)
            {
                //方法一、
                //object obj = AppDomain.CurrentDomain.CreateInstanceAndUnwrap("System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", tp.FullName);//这样可以
                //方法二、
                object obj = Activator.CreateInstance(tp);
                Control con = (Control)obj;
                con.Text = tp.Name;
                flowLayoutPanel1.Controls.Add(con); //将生成的控件添加到界面
            }
        }

        //需要填写包括命名空间的类型全名,例"System.Windows.Forms.Button"
        public static Type GetTypeByName(string fullName)
        {
            //获取应用程序用到的所有程序集
            var asy = AppDomain.CurrentDomain.GetAssemblies();
            for (int i = 0; i < asy.Length; i++)
            {
                //从对应的程序集中根据名字字符串找的对应的实体类型
                
                if (asy[i].GetType(fullName, false) != null)
                {
                    return asy[i].GetType(fullName, false);
                }
            }
            return null;
        }

    }
}

おすすめ

転載: blog.csdn.net/stephon_100/article/details/128217778