如何做供求網(wǎng)站企業(yè)培訓(xùn)課程設(shè)置
1、反射
反射是.NET Framework的一個特性,它允許在運行時獲取類型的信息以及動態(tài)創(chuàng)建對象,調(diào)用方法,以及訪問字段和屬性。
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、使用反射動態(tài)創(chuàng)建類型的實例Assembly assembly = Assembly.GetExecutingAssembly();Type type = assembly.GetType("ReflectionTest.Student");object StudentInstance = Activator.CreateInstance(type);//2、使用反射調(diào)用類型的字段FieldInfo fieldInfo = type.GetField("Name");string fieldValue = (string)fieldInfo.GetValue(StudentInstance);Console.WriteLine($"Student Name 字段值為{fieldValue}");//3、使用反射調(diào)用類型的屬性PropertyInfo propertyInfo = type.GetProperty("Sorce");int propertyValue = (int)propertyInfo.GetValue(StudentInstance);Console.WriteLine($"Student Name 屬性值為{propertyValue}");//4、使用反射調(diào)用類型的方法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 = "優(yōu)秀";}return level;}}
}
3、運行效果