当前位置: 首页> 房产> 市场 > C#反射基本应用

C#反射基本应用

时间:2025/7/15 1:21:15来源:https://blog.csdn.net/qq_27474555/article/details/140150719 浏览次数:0次

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、运行效果
在这里插入图片描述

关键字:C#反射基本应用

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: