C#如何使用反射实现通过字符串创建类

在做项目中碰到一个问题,就是如何在知道一个类的名字,如何创建这个类呢。做的一个小测试,直接贴代码了。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReflectFromStringToClass
{
    class Program
    {
        static void Main(string[] args)
        {
            
            string str = "A";
            Type type = Type.GetType(new Program().GetType().Namespace+"."+str,true,true);
            var temp= Activator.CreateInstance(type);
            A a = temp as A;
            a.PintA();
            
        }
    }
    public class A
    {
        public A()
        {
        }
        public void PintA()
        {
            Console.WriteLine("A");
        }
    }
       
}

猜你喜欢

转载自www.cnblogs.com/superfeeling/p/9198215.html