C#的反射中使用帶參的構造函數進行構建對象

隨便寫點代碼,發現了這個問題。。。

因爲一開始使用的Assembly.Load.CreateInstance是無法加參數的。。。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Configuration;

namespace DecorationClass
{
    class Player
    {
        public Player(string Name)
        {
            this._Name = Name;
            Console.WriteLine("1");

        }
        private readonly string _Name;

        public string Name
        {
            get { return _Name; }
        } 

    }
    class Program
    {
        static void Main(string[] args)
        {
            Player player1;
            string ClassName = ConfigurationManager.AppSettings["Player1"];
            string Name = ConfigurationManager.AppSettings["Player1Name"];
            //***************************************************************
            Assembly asm = Assembly.GetExecutingAssembly();
            object[] ObjArray = new object[1];
            ObjArray[0] = Name;
            player1 = (Player)asm.CreateInstance("DecorationClass." + ClassName, true, BindingFlags.Default, null, ObjArray, null, null);
        }
    }
}

從註釋的下面那行開始就是

現在才發現object是所有類的基類是多麼的重要。。。

這裏面的傳參是通過一個一個object數組進行傳遞的,也就是ObjArray,所有的類型都可以,但是順序一定要按照構造函數的順序來存!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章