zoukankan      html  css  js  c++  java
  • 【.Net 学习系列】-- 反射的简单用法

    1. 新建两个项目:类库(Model)和控制台应用程序(ReflectTest)。
    2. 在【Model】中添加一个类【User】:
       1 namespace Model
       2 {
       3     public class User
       4     {
       5         public string Show()
       6         {   
       7             return "Test Reflect.";
       8         }
       9     }
      10 }
    3. 编译生成【Model】,并把生成的dll拷贝到【ReflectTest】项目下的【inDebug】文件夹里面。
    4. 实现反射:
       1 using System;
       2 using System.Reflection;
       3 
       4 namespace ReflectTest
       5 {
       6     class Program
       7     {
       8         static void Main(string[] args)
       9         {
      10             Assembly assembly = Assembly.Load("Model");     // 1. 动态加载dll
      11             Type userType = assembly.GetType("Model.User");      // 2. 找到具体类型
      12             object instance = Activator.CreateInstance(userType);      // 3. 给类型创建一个对象
      13 
      14             // 解析dll
      15             {
      16                 // 获取程序集中的所有类型
      17                 foreach (Type type in assembly.GetTypes())
      18                 {
      19                     Console.WriteLine(type.Name);
      20                 }
      21 
      22                 // 获取类型中所有方法
      23                 foreach (MethodInfo method in userType.GetMethods())
      24                 {
      25                     Console.WriteLine(method.Name);
      26                 }
      27             }
      28 
      29             MethodInfo showMethod = userType.GetMethod("Show"); // 4. 获取指定方法
      30             var result = showMethod.Invoke(instance, null);     // 5. 方法调用
      31             Console.WriteLine(result);
      32 
      33             Console.ReadLine();
      34         }
      35     }
      36 }
  • 相关阅读:
    使用阿里云docker加速器
    Linux之screen命令详解
    Linux下Git和GitHub使用方法总结
    CentOS 6&7安装ffmpeg
    用yum安装lamp和lnmp环境
    nginx错误日志error_log日志级别
    CentOS7 yum 安装mysql 5.6
    python实现对数据的写入和读取(excel)
    windows下配置sublime
    远程配置pycharm
  • 原文地址:https://www.cnblogs.com/elliot-lei/p/5584306.html
Copyright © 2011-2022 走看看