static void Main(string[] args)
{
Student stu = new Student()
{
Id = 1,
StudentAddress="北京",
StudentName="C#程序"
};
Console.WriteLine("---------------- 通过反射操作字段和属性等成员-----------");
Assembly assembly = Assembly.LoadFrom("DB.MySqlClass.dll"); //加载方式三,完全限定名
Type type = assembly.GetType("DB.MySqlClass.Student"); //获取到类型名称3个参数。
object oStudent = Activator.CreateInstance(type); //实例化类型
foreach (var prop in type.GetProperties())
{
Console.WriteLine($"{prop.PropertyType},{prop.Name}, {prop.GetValue(stu)}");
Console.WriteLine("-----------------------------------------------------");
if (prop.Name.Equals("Id"))
{
prop.SetValue(stu, 2);
}
if (prop.Name.Equals("StudentName"))
{
prop.SetValue(stu, "PLC知识");
}
if (prop.Name.Equals("StudentAddress"))
{
prop.SetValue(stu, "上海");
}
Console.WriteLine($"{prop.PropertyType},{prop.Name}, {prop.GetValue(stu)}");
}
//方式二
//PropertyInfo[] propertyInfos = type.GetProperties();//查找所有的属性
//PropertyInfo propertyInfo = type.GetProperty("Id"); //查找Id的属性
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DB.MySqlClass
{
public class Student
{
public int Id { get; set; }
public string StudentName { get; set; }
public string StudentAddress { get; set; }
public int age;
public void Test()
{
}
}
}