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();  
            }  
        }  
    }  
  • 相关阅读:
    Web Site 与 Web Application 的区别
    Jquery获取text,areatext,radio,checkbox,select值
    C#怎么样操作world文档中的文字型窗体域?
    DataFormatString 用法
    overload和override的区别
    Apollo安装
    工控机基础
    CAN总线技术基础
    dd命令_Linux dd命令:复制(拷贝)文件,并对原文件进行转换
    Unity2021零基础入门教程
  • 原文地址:https://www.cnblogs.com/ThatsMyTiger/p/7207125.html
Copyright © 2011-2022 走看看