zoukankan      html  css  js  c++  java
  • C# Activator.CreateInstance 动态创建类的实例(一)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Kernel.SimpleLibrary
    {
        public class Person
        {
            private string name;
    
            public Person(){ }
    
            public Person(string name)
            {
                this.name = name;
            }
    
            public string Name
            {
                get { return this.name; }
                set { this.name = value; }
            }
    
            public override string ToString()
            {
                return this.name;
            }
        }
    }
    using System;
    using System.Reflection;
    using System.Runtime.Remoting;
    
    public class Program
    {
       static void Main(string[] args)
       {
            //创建在指定程序集中定义的指定类型的新实例
            //assemblyName = 命名空间,typeName = 命名空间.类名
            ObjectHandle handle = Activator.CreateInstance("Kernel.SimpleLibrary", "Kernel.SimpleLibrary.Person");
            Object p = handle.Unwrap();
            Type t = p.GetType();
            PropertyInfo prop = t.GetProperty("Name");
            if (prop != null)
                prop.SetValue(p, "Hello world!");
    
            MethodInfo method = t.GetMethod("ToString");
            Object retVal = method.Invoke(p, null);
            if (retVal != null)
                Console.WriteLine(retVal);
       }
    }
  • 相关阅读:
    jQuery源码 support
    jQuery 源码: 延迟对象补充。
    web FG interview all
    Img load
    浅谈js中this指向问题
    浅谈ES6原生Promise
    BootStrap的两种模态框方式
    让div盒子相对父盒子垂直居中的几种方法
    normalize与reset
    JS实现继承的方式
  • 原文地址:https://www.cnblogs.com/rinack/p/5831200.html
Copyright © 2011-2022 走看看