反射需要先用動態的方式,尋找類別的名稱,
才能正確解析出他所使用的類別。
一開始的程式 是參考 slashlook 的這篇程式碼。
但就是跑不起來,在建立類別的執行個體時,會發生錯誤,該值不能為null
 string cTargetClassName = "Sample_Reflection.Program.Transportation"; 
 System.Object oTemp = System.Activator.CreateInstance(System.Type.GetType(cTargetClassName));
  在stackOverflow查到一篇文章
看到有人使用typeof,就想到利用typeof去查目前clss的正確型別,
果然一整個神奇阿(有人知道原因為何還請告訴我)。
1.在程式執行期間,下中斷點。
2.到即時運算視窗輸入 上面圖片藍色底的部份
typeof(XXX) ,XXX要輸入類別名稱。
3.看到FullName的整個字串,他就是你要查的類別名稱..
4.直接使用Type.getType(字串) ,就能夠建立實體了。
完整程式碼修改如下:
 namespace Sample_Reflection
{
    class Program
    {
        static void Main(string[] args)
        {
            //使用者輸入
            System.Console.Write("請輸入您的交通工具類型(1.摩托車;2.汽車):");
            int iMachineType = System.Convert.ToInt32(System.Console.ReadLine());
            System.Console.Write("請輸入您的交通工具匿稱:");
            string cTargetName = System.Console.ReadLine();
 
            string cTargetClassName = "Sample_Reflection.Program+Transportation";
            
            string cTargetProperty = "Name";
            string cTargetMethodName = "Wheels";
             System.Object oTemp = System.Activator.CreateInstance(System.Type.GetType(cTargetClassName));
            System.Type oTypeBase = System.Type.GetType(cTargetClassName);
             //設定與展示物件的名稱屬性
            System.Reflection.PropertyInfo oProperty = oTypeBase.GetProperty(cTargetProperty);
            oProperty.SetValue(oTemp, cTargetName);
            System.Console.Write("您的愛車{0}", oProperty.GetValue(oTemp));
             //依使用者選擇的「字串」,動態轉換物件去調用介面成員
            System.Object oEntity;
            switch (iMachineType)
            {
                case 2:
                    oTypeBase = System.Type.GetType("Sample_Reflection.Program+ICar");
                    oEntity = (ICar)oTemp;
                    break;
                default:
                    oTypeBase = System.Type.GetType("Sample_Reflection.Program+IBike");
                    oEntity = (IBike)oTemp;
                    break;
            }
            System.Reflection.MethodInfo oMethod = oTypeBase.GetMethod(cTargetMethodName);
            System.Console.WriteLine("擁有{0}顆輪子。", oMethod.Invoke(oEntity, null));
             System.Console.Read();
        }
        class Transportation : ICar, IBike
        {
            public string Name { get; set; }
            int ICar.Wheels() { return 4; }
            int IBike.Wheels() { return 2; }
        }
         //小客車介面
        interface ICar
        {
            int Wheels();
        }
         //機踏車介面
        interface IBike
        {
            int Wheels();
        }
    }
}
 結論:
同一個namespace底下要 用getType 取得下一層的東西要用 +
測試環境:
vs2015 community
Framework:4.5.2
1/11 補充:關於+號的意思,參考MSDN
| 分隔符號 | 意義 | 
| 反斜線 (\) | 逸出字元。 | 
| 倒單引號 (') | 前面有一個或多個代表型別參數,位於泛型型別名稱結尾的數字的數字。 | 
| 括號 ([]) | 括住的泛型型別引數清單,建構的泛型型別。在型別引數清單中,將組件限定的型別。 | 
| 逗號 (,) | 後面接著組件名稱。 | 
| 句號 (.) | 代表命名空間識別項。 | 
| 加號 (+) | 前面有巢狀的類別。 | 
 
 
 

 
 
0 意見:
張貼留言