• c#反射机制


    例子:

    using System;
    using System.Collections.Generic; using System.Linq; using System.Text; namespace ITOO.Reflection.Student { public class Student { public string Name { get; set; } public int Age { get; set; } // 默认构造函数 public Student() { this.Age = 24; this.Name = "连江伟"; } //带参数的构造函数 public Student(string name,int age) { this.Name = name; this.Age = age; } public void Hello() { Console.WriteLine("我是"+Name +",我今年"+Age +"岁了!"); } } }

    利用反射操纵这个类 

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
    using System.Reflection;  
      
    namespace ITOO.Reflection.Client  
    {  
        class Program  
        {  
            static void Main(string[] args)  
            {  
                //动态加载DLL,这个LoadFile最方便,参数就是dll的路径。  
                var asm = Assembly.LoadFile(@"C:UsersljwDesktop学习例子ITOO.Reflection.TestITOO.Reflection.StudentinDebugITOO.Reflection.Student.dll");  
                //获取Student类的类型  
                var type = asm.GetType("ITOO.Reflection.Student.Student");  
                //创建该类的实例  
                var instance = asm.CreateInstance("ITOO.Reflection.Student.Student");  
                //为学生类的属性赋值  
                type.GetProperty("Name").SetValue(instance, "段天涯", null);  
                type.GetProperty("Age").SetValue(instance, 18, null);  
                //获取Student类的方法  
                var method = type.GetMethod("Hello");  
                //调用Student类的成员方法Hello  
                method.Invoke(instance, null);  
                Console.Read();  
            }  
        }  
    }  
  • 相关阅读:
    git 命令手册
    leetcode #7 revert integer 问题
    leetcode #1 twoSum问题:简单实用哈希表
    c++模板函数分离编译的问题
    matlab 与c/c++ 混合MEX的编程
    springboot项目打war包
    springboot-jpa多数据源
    springboot使用RestTemplate+httpclient连接池发送http消息
    IDEA如何安装lombok
    Springboot如何启用文件上传功能
  • 原文地址:https://www.cnblogs.com/ThatsMyTiger/p/7207125.html
Copyright © 2020-2023  润新知