zoukankan      html  css  js  c++  java
  • [C#]动态创建对象

    参考链接:

    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 }

    输出:

  • 相关阅读:
    Java main方法继承
    MySQL 事务
    数据库日志文件和内存刷新机制
    MySQL 存储过程
    MySQL 索引
    JVM锁优化
    JVM字节码执行引擎和动态绑定原理
    虚拟机类加载机制
    JVM内存分配与回收
    JVM垃圾收集器
  • 原文地址:https://www.cnblogs.com/lyh916/p/11967343.html
Copyright © 2011-2022 走看看