码迷,mamicode.com
首页 > Windows程序 > 详细

[C#]通过反射动态创建对象

时间:2019-12-01 20:48:29      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:on()   exe   private   int   tar   小明   cti   通过   动态创建   

参考链接:

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 }

 

输出:

技术图片

[C#]通过反射动态创建对象

标签:on()   exe   private   int   tar   小明   cti   通过   动态创建   

原文地址:https://www.cnblogs.com/lyh916/p/11967343.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!