首页 > Windows开发 > 详细

[C#]动态创建对象

时间:2019-12-01 22:03:46      阅读:110      评论:0      收藏:0      [点我收藏+]

参考链接:

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#]动态创建对象

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!