反射 Assembly和Activator配合使用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Assembly和Activator配合使用
{
    class Program
    {
        public static List<car> m_listCard = new List<car>();
        static void Main(string[] args)
        {
            //Assembly.LoadFrom(stringPATH);也可以读取本地DLL
            string strName = "dazhong";//子类名称
               Assembly assembly = Assembly.GetAssembly(typeof(car));//获取程序集DLL,版本号等等-----
            Type card = assembly.GetType("Assembly和Activator配合使用."+ strName);//获取 命名空间+子类名称的类
            //如果这个类有构造函数进行赋值和匹配,如果没有就执行Activator.CreateInstance(card) as car);
            object[] obj = new object[2] { "我是构造函数的参数 ",2 };
            m_listCard.Add(Activator.CreateInstance((card), obj) as car);//使用与指定参数匹配程度最高的构造函数创建指定类型的实例。//相当于NEW新实例
            m_listCard.ToArray()[0].outcar();//新实例下面的方法调用演示
        }
    }
    public abstract class car//抽象类
    {
        public car(string a,int b)
        {
           // Console.WriteLine(a+b);
        }
        public abstract void outcar();
    }
    public class dazhong : car//大众子类
    {
        public dazhong(string aw, int b) : base(aw, b)

        {
            Console.WriteLine(aw + b);
        }
        public override void outcar()
        {
            Console.WriteLine("生产一辆大众汽车");
        }
    }
    public class aodi : car//奥迪子类
    {
        public aodi(string aw, int b) : base(aw, b)
        {
            Console.WriteLine(aw + b);
        }
        public override void outcar()
        {
            Console.WriteLine("生产一辆奥迪汽车");
        }
    }
}

Assembly 负责获取类。Activator负责 new类

 

form类,装B调用

Object obj = Activator.CreateInstance(t);//创建实例化
            this.formObjects.Add(obj);//被实例化的窗体添加到List
            formNum += 1;//窗体计数
            //下面出现了装B写法
            // t.InvokeMember("MdiParent", BindingFlags.SetProperty, null, obj, new object[] { this });//设定属性:分配from父窗体
            ((Form)obj).MdiParent = this;


            // t.InvokeMember("Text", BindingFlags.SetProperty, null, obj, new object[] { t.FullName + "  窗体:" + formNum });//
            ((Form)obj).Text = t.FullName + "  窗体:" + formNum;

            //t.InvokeMember("Show", BindingFlags.InvokeMethod, null, obj, new object[] { });//=((Form)obj).Show();
            ((Form)obj).Show();

 

posted @ 2021-06-04 11:05  灰色淡季  阅读(68)  评论(0)    收藏  举报