百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

C#自学——反射(Reflection) c#反射的优缺点

yuyutoo 2024-11-12 14:58 9 浏览 0 评论

反射是很多框架都用到的东西,是从0.25到0.5的一个进阶

反射可以动态创建对象,动态赋值,动态调用方法

反射可以在运行时获得类的信息

每个类都有一个 type对象,构造方法对应的是 ConstructorInfo对象,方法对应的是 MethodInfo对象,字段对应的是 FieldInfo对象,属性对应的是 PropertyInfo对象,使用时需要引用using System.Reflection;

Type

class Dog:Animal
{
  public string name;
  public int age;
  double price;
  static double weight;
  public Dog() { }
  public Dog(string name) { }
  public Dog(string name,int age) { }

  public override void Say() { }

  public double Price { get; set; }
  public double Weight { get; set; }
}

class Animal
{
  public virtual void Say() { }
}

class Print
{
  static void Main()
  {
    Dog dog = new Dog();

    // 获取类的 type 对象常用的三种方式
    Type type = typeof(Dog);
    Type type1 = dog.GetType();
    Type type2 = Type.GetType("Application.Dog");

    //假设只知道类的名字,利用类名创建对象实例
    Type t = typeof(Dog);
    // Activator.CreateInstance(t); 被实例化的对象必须有无参构造方法,没有则会抛出 MissingMethodException 缺失方法异常
    object dog1 = Activator.CreateInstance(t); // 相当于 new Dog();,由于返回的是 object ,所以只能用 object 接收

    Console.WriteLine(dog1);
    Console.WriteLine(t.BaseType); // 获取父类
    Console.WriteLine(t.Name); // 获取类名
    Console.WriteLine(t.FullName); // 获取全名,包含命名空间
    Console.WriteLine(t.IsAbstract); // 判断是否为 抽象类
    Console.WriteLine(t.IsArray); // 是否为 数组
    Console.WriteLine(t.IsClass); // 是否为 普通类
    Console.WriteLine(t.IsEnum); // 是否为 枚举
    Console.WriteLine(t.IsPublic); // 是否为 public
    Console.WriteLine(t.IsValueType); // 是否为 值类型
    Console.WriteLine("------------* 构造方法 *---------------");

    // 获取无参构造方法 t.GetConstructor(new Type[0]); 参数要求是 type对象数组,因此无参构造就只需要入参长度为 0 的数组就好了
    ConstructorInfo c1 = t.GetConstructor(new Type[0]);
    Console.WriteLine(c1); // Void .ctor ctor是IL里面构造方法的表现方式

    // 获取参数类型为 string 的构造方法
    c1 = t.GetConstructor(new Type[] { typeof(string) });
    Console.WriteLine(c1);

    // 获取参数类型为 string,int 的构造方法
    c1 = t.GetConstructor(new Type[] { typeof(string), typeof(int) });
    Console.WriteLine(c1);
    Console.WriteLine("------------* 字段 *---------------");

    // 获取所有字段,必须是public,获取的是未封装的字段
    FieldInfo[] f1 = t.GetFields();
    foreach (var field in f1)
    {
      Console.WriteLine(field);
    }

    // 获取 非public,且 非static 的字段,如果需要获取 static的,把Instance改成static
    f1 = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
    foreach (var field in f1)
    {
      Console.WriteLine(field);
    }
    Console.WriteLine("------------* 方法 *---------------");

    // 获得所有方法
    MethodInfo[] m1 = t.GetMethods();
    foreach (var method in m1)
    {
      Console.WriteLine(method);
    }
    // 获得指定方法
    // 注:如果方法有重载,则抛出 AmbiguousMatchException
    MethodInfo m2 = t.GetMethod("Say");
    Console.WriteLine("\n"+m2);
    // 解决方法抛出 AmbiguousMatchException异常
    m2 = t.GetMethod("Say",new Type[0]); // 获取无参方法
    m2 = t.GetMethod("Say",new Type[] { typeof(string)}); // 获取参数为 string 的方法
    Console.WriteLine("------------* 属性 *---------------");

    // 获得属性,获取到的是封装过的属性
    PropertyInfo[] prop = t.GetProperties();
    foreach (var p in prop)
    {
      Console.WriteLine(p);
    }
	}
}

输出:

Application.Dog
Application.Animal
Dog
Application.Dog
False
False
True
False
False
False
------------* 构造方法*---------------
Void.ctor()
Void .ctor(System.String)
Void .ctor(System.String, Int32)
------------* 字段*---------------
System.String name
System.Int32 age
System.Double price
System.Double<Price> k__BackingField
System.Double<Weight> k__BackingField
------------* 方法*---------------
Void Say()
Double get_Price()
Void set_Price(Double)
Double get_Weight()
Void set_Weight(Double)
Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()
System.String ToString()

Void Say()
------------* 属性*---------------
Double Price
Double Weight

反射示例 1

class Dog
{
  public string name;

  public void Say() { Console.WriteLine("你好,"+Name); }
  public void Say(string name) { Console.WriteLine(#34;你好,{name}"); }
  public string Name { get; set; }
}

class Print
{
  // 反射示例
  static void Main()
  {
    // 创建对象
    Type t = typeof(Dog);
    object obj = Activator.CreateInstance(t); // 创建对象,调用无参构造(方法1)
    object obj1 = t.GetConstructor(new Type[0]).Invoke(new object[0]); // 获得对象的无参构造,调用(方法2)

    // 给属性赋值
    PropertyInfo prop = t.GetProperty("Name"); // 获得属性
    prop.SetValue(obj, "大宝"); // 赋值

    // 调用方法
    MethodInfo method = t.GetMethod("Say", new Type[0]); // 获得无参方法
    MethodInfo method1 = t.GetMethod("Say", new Type[] { typeof(string) }); // 获得有参方法

    method.Invoke(obj, new object[0]); // 调用无参方法
    method1.Invoke(obj, new object[] { "Tom" }); // 调用有参方法并赋值
  }
}

输出:

你好,大宝
你好,Tom

反射示例 2

class Dog
{
  public string name;

  public void Say() { Console.WriteLine("你好,"+Name); }
  public void Say(string name) { Console.WriteLine(#34;你好,{name}"); }
  public string Name { get; set; }
}
class Print
{
  static void Main()
  {
    Dog dog = new Dog();
    dog.Name = "Tom";
    Show(dog);
  }

  static void Show(object obj)
  {
    Type t = obj.GetType();

    PropertyInfo[] prop = t.GetProperties();
    foreach (var p in prop)
    {
      if (p.CanRead)
      {
        string name = p.Name;
        object value = p.GetValue(obj);
        Console.WriteLine(name+"="+value);
      }
    }
  }
}

输出:

Name=Tom

反射示例3 (复制对象的值)(浅拷贝--仅复制对象的值,不是同一个对象)

class Dog
{
  public string name;

  public string Name { get; set; }
}
class Print
{
  static void Main()
  {
    Dog dog = new Dog();
    dog.Name = "Tom";
    object dog1 = Clone(dog);
    Console.WriteLine(object.ReferenceEquals(dog,dog1)); // 判断是否为同一个对象
  }

  static object Clone(object obj)
  {
    Type t = obj.GetType();
    object newObject = Activator.CreateInstance(t); // 创建对象

    PropertyInfo[] prop = t.GetProperties();
    foreach (var p in prop)
    {
      if (p.CanRead&&p.CanWrite)
      {
        object value = p.GetValue(obj);
        p.SetValue(newObject, value);
      }
    }
    return newObject;
  }
}

输出:

False

相关推荐

java把多张图片导入到PDF文件中(java如果导入图片到项目)

packagecom.mlh.utils;importcom.itextpdf.text.*;importcom.itextpdf.text.Font;importcom.itextp...

聊聊langchain4j的AiServicesAutoConfig

序本文主要研究一下langchain4j-spring-boot-starter的AiServicesAutoConfig...

Spring 中三种 BeanName 生成器!(spring生成bean过程)

无论我们是通过XML文件,还是Java代码,亦或是包扫描的方式去注册Bean,都可以不设置BeanName,而Spring均会为之提供默认的beanName,今天我们就来看看Spr...

Zookeeper实现微服务统一配置中心

Zookeeper介绍本质它是一个分布式服务框架,是ApacheHadoop的一个子项目...

Spring cloud Gateway 动态路由(springboot gateway 动态路由)

一、分析过程...

从Nacos客户端视角来分析一下配置中心实现原理

目录...

Python 中容易被新手忽略的问题(python容易犯的错误)

设置全局变量有时候设置全局变量的需求并不是直接赋值,而是想从某个数据结构里引用生成,可以用下面这两种方法,推荐第二种,golbals()支持字典用法很方便。...

Springboot实现对配置文件中的明文密码加密

我们在SpringBoot项目当中,会把数据库的用户名密码等配置直接放在yaml或者properties文件中,这样维护数据库的密码等敏感信息显然是有一定风险的,如果相关的配置文件被有心之人拿到,必然...

是时候丢掉BeanUtils了(丢掉了时间)

前言为了更好的进行开发和维护,我们都会对程序进行分层设计,例如常见的三层,四层,每层各司其职,相互配合。也随着分层,出现了VO,BO,PO,DTO,每层都会处理自己的数据对象,然后向上传递,这就避免不...

EasyExcel自定义合并单元格多行合并根据自定义字段

第一种方式实现通过定义注解+实现RowWriteHandler接口中的afterRowDispose方法来动态合并行根据指定的key可以是单个字段也可以是多个字段也可以根据注解指定。注解方式使用参考原...

太香了!女朋友熬夜帮我整理的Spring Boot - Banner 笔记,分享给你

上一篇分享的是《Java避坑指南!IDEA查看.class文件源码下载失败问题汇总》,这篇给大家分享《SpringBoot-自定义Banner图案》。...

基于SpringCloud的enum枚举值国际化处理实践

背景选用SpringCloud框架搭建微服务做业务后台应用时,会涉及到大量的业务状态值定义,一般常规做法是:持久层(数据库)存储int类型的值后台系统里用阅读性好一点儿的常量将int类型的值做一层映射...

Lucene就是这么简单(好女婿你以后就是妈妈的老公了)

什么是Lucene??Lucene是apache软件基金会发布的一个开放源代码的全文检索引擎工具包,由资深全文检索专家DougCutting所撰写,它是一个全文检索引擎的架构,提供了完整的创建索引和...

注解@Autowired和@Resource的区别总结

零、前言@Autowired和@Resource注解都可以在Spring应用中进行声明式的依赖注入。以前都是看的网上关于两者的区别,但是实际和网上说的有出入,故从源码角度进行分析、验证。...

100个Java工具类之73:系统信息获取工具类SystemUtils

SystemUtils是一个功能强大的工具类。可以获取系统属性、检测java版本、处理跨平台文本文件,合理地使用此类,可以使代码更健壮,系统更安全。...

取消回复欢迎 发表评论: