zoukankan      html  css  js  c++  java
  • 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();  
            }  
        }  
    }  
  • 相关阅读:
    Dojo(发音:豆粥)的目标是解决DHTML应用程序长期存在的历史问题
    如何用Fireworks制作图标的透明效果
    2021.09.15膜你赛
    2021.09.14 膜你赛
    2021.08.29 膜你赛
    2021.08.28 膜你赛
    2021.10.06 膜你赛
    2021.09.18 膜你赛
    2021.09.13膜你赛
    2021.10.05膜你赛
  • 原文地址:https://www.cnblogs.com/ThatsMyTiger/p/7207125.html
Copyright © 2011-2022 走看看