C# Activator.CreateInstance 动态创建类的实例(一)

原文:C# Activator.CreateInstance 动态创建类的实例(一)

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;
        }
    }
}
C# Activator.CreateInstance 动态创建类的实例(一)
C# Activator.CreateInstance 动态创建类的实例(一)
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);
   }
}
C# Activator.CreateInstance 动态创建类的实例(一)

 

C# Activator.CreateInstance 动态创建类的实例(一)

上一篇:WIN Server 2012 添加角色失败


下一篇:flash怎样生成exe文件? flash发布成exe文件的图文教程