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