我正在学习有关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");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句