C# 反射之動態創建對象


引言:

       C# 動態創建對象只要有兩大類  Activator 和 Assembly 。

Activator 類
       Activator 類提供好幾個動態創建對象的重載方法。

1:public static object CreateInstance(Type type);
2:public static object CreateInstance(Type type, params object[] args);

 

動態創建對象主要接受的參數為Type,而獲取Type對象有三種方式

 1:Type type = Type.GetType("命名空間名稱.類名");
 2:Type type = typeof("類名");
 3:Person p = new Person(); //通過對象來進行創建type
  Type type = p.GetType(); 

兩種方法區別僅為:創建無參數的構造方法和創建有參數的構造函數。

  Type type = typeof(Person);
            var p = Activator.CreateInstance(type) as Person;

public class Person
    {
        public Person()
        {

        }
        public Person(string name, int age)
        {
            this.Name = name;
            this.Age = 1;
        }
        public string Name { set; get; }
        public int Age { set; get; }
        public void SayHello()
        {
            Console.WriteLine("你好");
        }
    }

  動態創建創建有參數的構造函數

Type type = typeof(Person);
            var p = Activator.CreateInstance(type,new object[] { "xiaohong",1}) as Person;
            Console.WriteLine(p.Name);

Assembly 類

  //Assembly ass = Assembly.Load(Assembly.GetExecutingAssembly().FullName);  知道當前創建的對象是當前程序集
           // Assembly ass = Assembly.LoadFile(@"程序集的全路徑");  
            Assembly ass = Assembly.LoadFrom(@"程序集的全路徑");
 // LoadFile和LoadFrom 區別是 LoadFrom它會載入dll文件及其引用的其他dll,而LoadFile 只載入相應的dll文件
            Type type = null;
            ass.GetTypes().ToList().ForEach(i =>
            {
                if (i.IsClass && i.IsPublic && i.Name == "Person")
                {
                    type = i;
                }
            });
            var p = Activator.CreateInstance(type, new object[] { "xiaohong", 1 }) as Person;
            Console.WriteLine(p.Name);
            Console.ReadKey();

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM