实体类:
public class Student
{
/// <summary>
/// 学号
/// </summary>
[DisplayName("学号")]
public string ID { get; set; } = "002";
/// <summary>
/// 姓名
/// </summary>
[DisplayName("姓名")]
public string Name { get; set; } = "张三";
/// <summary>
/// 分数
/// </summary>
[DisplayName("分数")]
public decimal Score { get; set; } = 90;
}
Assembly assembly = Assembly.GetExecutingAssembly(); // 获取当前程序集
object student = assembly.CreateInstance(textBox1.Text); // 创建类的实例 传入“类的完全限定名(即包括命名空间)”
PropertyInfo[] propertyInfos = student.GetType().GetProperties(); //获取对象所有属性
Dictionary<string, object> dic = new Dictionary<string, object>();
richTextBox1.Text += "类名:" + textBox1.Text+"\r\n";
foreach (var p in propertyInfos)
{
var displayname = p.GetCustomAttribute<DisplayNameAttribute>().DisplayName; //获取属性DisplayName
var name = p.Name;
var value = student.GetType().GetProperty(p.Name).GetValue(student, null);//通过属性名获取对象的值
richTextBox1.Text +="属性名:"+ p.Name + " ;Displayname的值:"+ displayname + " ;属性值:"+value+"\r\n";
}