lyh916

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

参考链接:

https://www.cnblogs.com/codejgq/articles/10163584.html

http://www.360doc.com/content/18/0524/09/51449331_756581126.shtml

https://www.cnblogs.com/soundcode/p/10722863.html

 

代码如下:

 1 using System;
 2 using System.Reflection;
 3 using UnityEngine;
 4 
 5 public class Person
 6 {
 7     private string name;
 8     private int age;
 9 
10     public Person()
11     {
12     }
13 
14     public Person(string name, int age)
15     {
16         this.name = name;
17         this.age = age;
18     }
19 
20     public void PrintInfo()
21     {
22         Debug.Log(string.Format("name: {0} age: {1}", name, age));
23     }
24 }
25 
26 public class TestReflection : MonoBehaviour
27 {
28     void Start()
29     {
30         Type type = typeof(Person);
31 
32         //无参
33         Person p1 = Activator.CreateInstance(type) as Person;
34         p1.PrintInfo();
35 
36         //有参
37         Person p2 = Activator.CreateInstance(type, new object[] { "小明", 30}) as Person;
38         p2.PrintInfo();
39 
40         //程序集
41         Type type2 = Assembly.GetExecutingAssembly().GetType("Person");
42         Person p3 = Activator.CreateInstance(type2, new object[] { "小张", 50 }) as Person;
43         p3.PrintInfo();
44     }
45 }

 

输出:

posted on 2019-12-01 19:56  艰苦奋斗中  阅读(1092)  评论(0编辑  收藏  举报