首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 反射應用實戰(二):ShowObject 核心類別完整測試驗證

     編輯:關於C語言

測試場景

本文提供完整的 Console 應用程式,驗證 ShowObject 類別的所有核心功能:動態載入型別、列舉屬性、設定/取得屬性值、呼叫方法。

測試代碼完整列表

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Model;
using ObjectLoader;

namespace ReflectionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            ShowObject showObj = new ShowObject();
            
            // 1. 動態載入 UserInfo 型別並建立實例
            object obj = showObj.LoadObject("UserInfo");
            Console.WriteLine("實例完整型別名:" + obj.GetType().FullName);

            // 2. 列舉所有公共屬性
            Console.WriteLine("實例的所有公共屬性:");
            PropertyInfo[] pInfos = showObj.GetPropertys(obj);
            foreach (PropertyInfo info in pInfos)
            {
                Console.WriteLine(info.PropertyType + " : " + info.Name);
            }

            // 3. 設定屬性值
            showObj.SetPropertyValue(obj, "UserId", 1);
            showObj.SetPropertyValue(obj, "UserName", "admin");

            // 4. 驗證屬性值
            Console.WriteLine("設定屬性值後的結果:");
            Console.WriteLine("UserId   : " + showObj.GetPropertyValue(obj, "UserId"));
            Console.WriteLine("UserName : " + showObj.GetPropertyValue(obj, "UserName"));

            // 5. 動態呼叫方法
            Console.WriteLine("執行實例方法 Show():");
            showObj.ExecuteMethod(obj, "Show");
        }
    }
}

執行結果說明

程式輸出如下圖所示,依序顯示:

  1. 實例型別:Model.UserInfo
  2. 屬性清單:Int32 : UserId、String : UserName
  3. 設定後數值:UserId: 1、UserName: admin
  4. 方法執行:控制台輸出 UserId:1, UserName:admin

反射測試執行結果截圖

測試驗證的核心能力

功能對應方法反射關鍵 API
動態建立實例LoadObjectAssembly.CreateInstance
列舉屬性GetPropertysType.GetProperties()
設定屬性值SetPropertyValuePropertyInfo.SetValue
讀取屬性值GetPropertyValuePropertyInfo.GetValue
動態呼叫方法ExecuteMethodMethodInfo.Invoke

結語

此測試完整驗證了反射操作物件的「建立、查詢、修改、執行」全生命週期,為後續資料庫映射、插件架構、動態代理等高階應用奠定基礎。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved