消费返利网站做的最长久的,河南郑州最新消息,深圳网站设计公司发展历程,济南网站建设全包1、反射 反射是.NET Framework的一个特性#xff0c;它允许在运行时获取类型的信息以及动态创建对象#xff0c;调用方法#xff0c;以及访问字段和属性。 2、代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Sy…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 outputmethodInfo.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、运行效果