I'm learning about C# reflection and ran into some road blocks along the way. I have an example problem where I'm trying to perform the following:
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 "";
}
}
Thanks in advance.
You're almost there; now just call SetValue on the property info:
//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");
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments