Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / C#

System.Reflection.FieldInfo: odniesienie praktyczne

System.Reflection.FieldInfo: odniesienie praktyczne: FieldInfo opisuje pole i pozwala odczytać lub ustawić jego wartość refleksyjnie.

Wersja: .NET API; verified against .NET 10 reference surface

Składnia

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

FieldInfo opisuje pole i pozwala odczytać lub ustawić jego wartość refleksyjnie.

Stosuj w narzędziach metadanych, gdy typ pola nie jest znany statycznie.

SetValue omija część kontroli kompilatora i jest wolniejsze od dostępu bezpośredniego.

Dla pola statycznego parametr target/obj metod GetValue i SetValue jest ignorowany; przekazanie null jest konwencjonalne, lecz nie wymagane. Trimming może usunąć nieznane pola.

Kompletny program rzeczywiście używa System.Reflection.FieldInfo; oczekiwany stdout to dokładnie 8.

Przykłady

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; }

Wynik

8

Kompletny program rzeczywiście używa `System.Reflection.FieldInfo`; oczekiwany stdout to dokładnie `8`.

Źródła