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