根据类型名创建对象

1.概要

方式1

Assembly assembly = Assembly.GetExecutingAssembly(); // 获取当前程序集 
A a = (A)assembly.CreateInstance(t.FullName);

方式2 

A a = (A)Activator.CreateInstance(t.Namespace, t.FullName).Unwrap();

方式3 

Type type = Type.GetType(t.FullName);
A a = (A)c[0].Invoke(null);

2.代码

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

namespace 根据类型名创建对象
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("根据类型名创建对象");

            Program program = new Program();
            program.main();
            Console.ReadKey();
        }
        private void main() {
            test1(typeof(A));
            test2(typeof(A));
            test3(typeof(A));
        }
        //只使用Assembly
        private void test1(Type t) {
            Console.WriteLine("只使用Assembly");
            Assembly assembly = Assembly.GetExecutingAssembly(); // 获取当前程序集 
            A a = (A)assembly.CreateInstance(t.FullName);
            a.Fun();
        }
        //使用Activator和Type
        private void test2(Type t)
        {
            Console.WriteLine("使用Activator和Type");
            A a = (A)Activator.CreateInstance(t.Namespace, t.FullName).Unwrap();
            a.Fun();
        }
        //只使用Type
        private void test3(Type t)
        {
            Console.WriteLine("只使用Type");
            Type type = Type.GetType(t.FullName);
            {
                //这个不行 这是不包括构造函数吗?
                //var b = type.GetMethod(t.Name);
            }

            var c = type.GetConstructors();
            {
                //这种不行 应该是参数不对
                //A a = (A)type.GetMethod(t.Name).Invoke(null,null);
            }

            A a = (A)c[0].Invoke(null);
            a.Fun();
        }
    }
    public class A {
        public A() { }
        public void Fun() {
            Console.WriteLine("我是A,我在运行");
        }
    }
}

3.运行

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值