Reflection: Using PropertyInfo
//The PropertyInfo class discovers the attributes of a property and provides access to property metadata.
//The PropertyInfo class is very similar to the FieldInfo class and also contains the ability to set the value of the property on an instance.
//It also gives you the ability to individually receive the get and set accessors as MethodInfo classes through the GetAccessors method
Type myClassType = typeof(MyClass);
//Get public properties
System.Reflection.PropertyInfo[] propertyInfos = myClassType.GetProperties();
System.Reflection.MethodInfo[] accessorMethodInfos = propertyInfo.GetAccessors();
//Example
//Get all properties from class MyClass and output it`s name and accessors methods names
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public class Program
{
public static void Main()
{
var type = typeof(University.Student);
var propertyInfos = type.GetProperties();
foreach(var propertyInfo in propertyInfos)
{
Console.Write(propertyInfo.Name+" { ");
var accessors = propertyInfo.GetAccessors();
foreach(var accessor in accessors)
{
Console.Write(accessor.Name+"; ");
}
Console.WriteLine("}");
}
}
}
namespace University {
public class Student
{
public string FullName { get; set; }
public int Class { get; set; }
public DateTime DateOfBirth { get{ return _dateOfBirth; } }
private DateTime _dateOfBirth = DateTime.MinValue;
public string GetCharacteristics()
{
return "";
}
}
namespace Department {
public class Professor {
public string FullName { get; set; }
}
}
}
//Output
FullName { get_FullName; set_FullName; }
Class { get_Class; set_Class; }
DateOfBirth { get_DateOfBirth; }
//Exercise: Set Property Value Using Reflection
//1) Create new instance of Student
//2) Get instance type
//3) Get property FullName by name from type
//4) Set property value to "John Smith" using reflection
using System;
using System.Reflection;
public class Program
{
public static void Main()
{
var student = new Student();
var type = student.GetType();
PropertyInfo propertyInfo = type.GetProperty("FullName");
propertyInfo.SetValue(student, "John Smith");
Console.WriteLine(propertyInfo.GetValue(student));
}
}
public class Student
{
public string FullName { get; set; }
public int Class { get; set; }
public DateTime DateOfBirth { get; set; }
public string GetCharacteristics()
{
return "";
}
}