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");
        }
    }
       
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM