Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / C#

System.Reflection.FieldInfo: referência prática

System.Reflection.FieldInfo: referência prática: FieldInfo descreve um campo e permite ler ou definir o seu valor por reflexão.

Versão: .NET API; verified against .NET 10 reference surface

Sintaxe

System.Reflection.FieldInfo /* select a documented member or constructor */

FieldInfo descreve um campo e permite ler ou definir o seu valor por reflexão.

Usa-o em ferramentas de metadados quando o tipo do campo não é conhecido estaticamente.

SetValue ignora algumas verificações do compilador e é mais lento do que o acesso direto.

Para um campo estático, GetValue e SetValue ignoram o parâmetro target/obj; passar null é convencional, não obrigatório. O trimming pode remover campos desconhecidos da análise.

O programa completo usa realmente System.Reflection.FieldInfo; o stdout exato esperado é 8.

Exemplos

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

var field = typeof(Sample).GetField(nameof(Sample.Value))!;
Console.WriteLine(field.GetValue(new Sample()));

sealed class Sample { public int Value = 8; }

Resultado

8

O programa completo usa realmente `System.Reflection.FieldInfo`; o stdout exato esperado é `8`.

Fontes