FieldInfo
Поле получают из
GetFields.
Чтение и запись -
GetValue
и
SetValue.
Для статического поля объект
можно передать null.
Синтаксис
FieldInfo field = type.GetField("Open");
Пример
Давайте прочитать имя поля
Open:
using System;
using System.Reflection;
class Gate
{
public int Open = 12345;
}
class Program
{
static void Main()
{
FieldInfo field = typeof(Gate).GetField("Open");
string res = field.Name;
Console.WriteLine(res);
}
}
Результат выполнения кода:
"Open"
Пример
Давайте прочитать значение поля:
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
Пример
Давайте прочитать статическое
поле с null:
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
Смотрите также
-
GetValue,
чтение -
SetValue,
запись -
PropertyInfo,
свойство -
BindingFlags,
флаги поиска