栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

根据类型名创建对象

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

根据类型名创建对象

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.运行

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/911104.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号