[英]How can I Get the property by name from type and Set Propert value using reflection in C#
我正在学习有关C#反射的知识,并在此过程中遇到了一些障碍。 我有一个示例问题,我尝试执行以下操作:
Student sT = new Student()
var getType = sT.GetType();
using System;
using System.Reflection;
public class Program
{
public static void Main()
{
//1. Create new instance of Stuedent
Student sT = new Student();
//2. Get instance type
var getType = sT.GetType();
var myStringProperties1 = getType.GetProperty("FullName",
typeof(string));
//3. Get property FullName by name from type ????
//4. Set property value to "Some Name" using reflection
}
}
public class Student
{
public string FullName { get; set; }
public int Class { get; set; }
public DateTime DateOfBirth { get; set; }
public string GetCharacteristics()
{
return "";
}
}
提前致谢。
你快到了; 现在只需在属性信息上调用SetValue即可:
//1. Create new instance of Student
Student student = new Student();
//2. Get instance type
var getType = student.GetType();
//3. Get property FullName by name from type
var fullNameProperty = getType.GetProperty("FullName",
typeof(string));
//4. Set property value to "Some Name" using reflection
fullNameProperty.SetValue(student, "Some Name");
您还可以遍历属性
foreach (var pro in getType.GetProperties()/* get all your properties*/)
{
var type = pro.GetType();//Property type
var propertyName= pro.Name;//Property name
pro.SetValue(toObject,value);//set Property value
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.