Метод GetValue
Первый аргумент - экземпляр,
для которого читают свойство.
Запись -
SetValue.
Синтаксис
object value = prop.GetValue(target);
Пример
Давайте прочитать Count:
using System;
using System.Reflection;
class Gate
{
public int Count { get; set; } = 12345;
}
class Program
{
static void Main()
{
Gate gate = new Gate();
PropertyInfo prop = typeof(Gate).GetProperty("Count");
int res = (int)prop.GetValue(gate);
Console.WriteLine(res);
}
}
Результат выполнения кода:
12345
Пример
Давайте прочитать значение после обычного присваивания:
using System;
using System.Reflection;
class Gate
{
public int Count { get; set; }
}
class Program
{
static void Main()
{
Gate gate = new Gate { Count = 12345 };
PropertyInfo prop = typeof(Gate).GetProperty("Count");
int res = (int)prop.GetValue(gate);
Console.WriteLine(res);
}
}
Результат выполнения кода:
12345
Пример
Давайте прочитать строковое свойство:
using System;
using System.Reflection;
class Gate
{
public string Name { get; set; } = "abcde";
}
class Program
{
static void Main()
{
Gate gate = new Gate();
PropertyInfo prop = typeof(Gate).GetProperty("Name");
string res = (string)prop.GetValue(gate);
Console.WriteLine(res);
}
}
Результат выполнения кода:
"abcde"
Смотрите также
-
SetValue,
запись -
PropertyType,
тип свойства -
PropertyInfo,
обзор -
FieldInfo.GetValue,
чтение поля