• 【C#基础】 反射


    记录一下放射的一些东西把,之前都是学了记在笔记本上,现在整理上来,当作是复习和知新。

    微软参考文档:

    https://docs.microsoft.com/zh-cn/dotnet/framework/reflection-and-codedom/reflection

    反射的实现主要依赖于微软提供的两个命名空间:System.Reflection 和System.Type 两个命名空间:

    反射:就是动态的获取程序集,并获取其中类型的元数据,然后访问该类型的过程。

    可以在运行时 创建 访问 调用 类型。

    反射在实际应用中通常被用于: 深复制实现,数据库DataTable 转换成执行的类型 等。

    情况①:当我们不知道对象的时候(T)我们通常使用下面的方式来获取某个类型的Type

    Type type=typeof(T);

    情况②:当我们已知某个对象的时候 我们可以直接使用GetType(),方法来获取指定对象类型的Type对象

    如:

    Person p=new Person();

    Type personType=p.GetType();

    1:获取类中的所有方法(不包括私有方法)

    MethodInfo[] methods=type.GetMethods();

    2:获取某个类型的所有属性(私有属性也无法获取到)

    PropertyInfo[] propertyInfo=type.GetProperties();

    3:获取类型的所有字段(私有字段也无法获取到)

    FieldInfo[] fields=type.GetFields();

    4:获取所有成员,不包括私有成员

    MemberInfo[] memberInfos=type.GetMembers();

    #通过反射来获取一个程序集的类型

    1:动态加载 .dll文件

    Assembly assembly=Assembly.LoadFile(@"文件路径")

    2:获取刚刚加载的程序集中的所有类型

    Type[] type=assembly.GetTypes();

    3:获取访问修饰符为 public的类型

    Type[] type =assembly.GetExportedTypes();:

    4:获取某个类的Type

    Type type=assembly.GetType("命名空间.类名");

    5:根据4中的type获取某个特定的方法(根据方法名)

    MethodInfo method=type.GetMethod("方法名");

    7:调用这个方法

    method.Invoke()

     8:通过反射来 创建某个类型的对象(其实就是通过类型的Type 来创建该类型的对象)

    object obj=Activator.CreateInstance(type);

    method.invoke(obj,null)

    三:通过反射获取类的属性,并赋值

    1:获取Name属性

    PropertyInfo property=type.GetProperty("Name");

    object obj=Activator.CreateInstance(property);

    2:为属性赋值

    property.SetValue(obj,"姓名",null)

    3:获取属性

    string  property=property.GetValue(obj,null).toString();

    四:构造函数

    ConstructorInfo ctor=type.GetConstructor(new Type[]{typeof(string),typeof(int)})

    调用构造函数

    object obj=ctor.Invoke(new object[]{"asdf","asdfas","125"});

    示例代码后面 在补充,先这样。

  • 相关阅读:
    vue-element-admin中table分页改为前台处理
    vue项目如何部署到Tomcat中
    vuex之modules 热加载(hot update)
    持续学习
    css比较特殊选择器汇总(持续更新)
    关于伪元素before after总结
    ajax入门-实现省份下拉框
    super和this关键字的详解
    监听器
    当浏览器被关闭时,session是否被关闭?
  • 原文地址:https://www.cnblogs.com/SignX/p/10878498.html
Copyright © 2020-2023  润新知