Метод GetValue
Для статического поля первый
аргумент может быть null.
Запись -
SetValue.
Синтаксис
object value = field.GetValue(target);
Пример
Давайте прочитать поле экземпляра:
using System;
using System.Reflection;
class Gate
{
public int Open = 12345;
}
class Program
{
static void Main()
{
Gate gate = new Gate();
FieldInfo field = typeof(Gate).GetField("Open");
int res = (int)field.GetValue(gate);
Console.WriteLine(res);
}
}
Результат выполнения кода:
12345
Пример
Давайте прочитать статическое поле:
using System;
using System.Reflection;
class Gate
{
public static int Token = 12345;
}
class Program
{
static void Main()
{
FieldInfo field = typeof(Gate).GetField(
"Token",
BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
int res = (int)field.GetValue(null);
Console.WriteLine(res);
}
}
Результат выполнения кода:
12345
Пример
Давайте прочитать строковое поле:
using System;
using System.Reflection;
class Gate
{
public string Name = "abcde";
}
class Program
{
static void Main()
{
Gate gate = new Gate();
FieldInfo field = typeof(Gate).GetField("Name");
string res = (string)field.GetValue(gate);
Console.WriteLine(res);
}
}
Результат выполнения кода:
"abcde"
Смотрите также
-
SetValue,
запись -
PropertyInfo.GetValue,
свойство -
FieldInfo,
обзор -
GetFields,
поиск поля