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);
   }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM