当前位置: 首页 > news >正文

C#反射基本应用

1、反射
反射是.NET Framework的一个特性,它允许在运行时获取类型的信息以及动态创建对象,调用方法,以及访问字段和属性。
2、代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;namespace ReflectionTest
{internal class Program{static void Main(string[] args){//1、使用反射动态创建类型的实例Assembly assembly = Assembly.GetExecutingAssembly();Type type = assembly.GetType("ReflectionTest.Student");object StudentInstance = Activator.CreateInstance(type);//2、使用反射调用类型的字段FieldInfo fieldInfo = type.GetField("Name");string fieldValue = (string)fieldInfo.GetValue(StudentInstance);Console.WriteLine($"Student Name 字段值为{fieldValue}");//3、使用反射调用类型的属性PropertyInfo propertyInfo = type.GetProperty("Sorce");int propertyValue = (int)propertyInfo.GetValue(StudentInstance);Console.WriteLine($"Student Name 属性值为{propertyValue}");//4、使用反射调用类型的方法MethodInfo methodInfo = type.GetMethod("Level");object output=methodInfo.Invoke(StudentInstance, new object[] { 80 });Console.WriteLine($"Student Level 方法返回值为{output}");Console.ReadKey();}}public class Student{public string Name = "Tom";public int Sorce { get; set; } = 91;public string Level(int score){string level = "";if (score < 60){level = "不及格";}else if (score < 80){level = "及格";}else if (score < 90){level = "良好";}else{level = "优秀";}return level;}}
}

3、运行效果
在这里插入图片描述

http://www.lryc.cn/news/390628.html

相关文章:

  • 1.英语中的从句学习
  • Perl语言简介
  • 【SpringBoot3】使用Jasypt加密数据库用户名、密码等敏感信息
  • 如何确定MySQL中哪些列适合做索引
  • C# winform中权限页面的设计和开发
  • 本地Windows电脑 连接 Windows 服务器
  • 【分布式计算框架 MapReduce】MapReduce 初级编程
  • VideoPrism——探索视频分析领域模型的算法与应用
  • Spring Boot项目的两种发布方式
  • Java中的服务注册与发现原理与实现
  • 【Python】成功解决TypeError: ‘float‘ object cannot be interpreted as an integer
  • Java面试八股文
  • 周周星分享7.3—基于气象大数据的自动站实况联合预测
  • 【密码学】面向小白的古典密码基础入门笔记
  • 【Qt】之【Bug】大量出现“未定义的标识符”问题
  • C++中的常成员函数
  • 小试牛刀-区块链代币锁仓(Web页面)
  • Geoserver源码解读五 Catalog
  • 安全与加密常识(5)自签名证书
  • Java官网网址及其重要资源
  • Linux--start-stop-daemon
  • 优化Java中XML和JSON序列化
  • 像学Excel 一样学 Pandas系列-创建数据分析维度
  • Rust 基础教程
  • Study--Oracle-06-Oracler网络管理
  • uniapp零基础入门Vue3组合式API语法版本开发咸虾米壁纸项目实战
  • 数字信号处理教程(2)——时域离散信号与时域离散系统
  • imx6ull/linux应用编程学习(8)PWM应用编程(基于正点)
  • 等保2.0 实施方案
  • 7/3 第六周 数据库的高级查询