Type.GetFields 메서드

정의

현재 Type필드를 가져옵니다.

오버로드

Name Description
GetFields()

현재 Type모든 공용 필드를 반환합니다.

GetFields(BindingFlags)

파생 클래스에서 재정의되는 경우 지정된 바인딩 제약 조건을 사용하여 현재 Type대해 정의된 필드를 검색합니다.

GetFields()

현재 Type모든 공용 필드를 반환합니다.

public:
 virtual cli::array <System::Reflection::FieldInfo ^> ^ GetFields();
public:
 cli::array <System::Reflection::FieldInfo ^> ^ GetFields();
public System.Reflection.FieldInfo[] GetFields();
abstract member GetFields : unit -> System.Reflection.FieldInfo[]
override this.GetFields : unit -> System.Reflection.FieldInfo[]
member this.GetFields : unit -> System.Reflection.FieldInfo[]
Public Function GetFields () As FieldInfo()

반품

현재TypeFieldInfo 대해 정의된 모든 공용 필드를 나타내는 개체의 배열입니다.

-또는-

현재Type에 대해 정의된 공용 필드가 없는 경우 형식FieldInfo의 빈 배열입니다.

구현

예제

다음 예제에서는 메서드를 사용하는 방법을 보여 있습니다 GetFields() .

using System;
using System.Reflection;
using System.ComponentModel.Design;

class FieldInfo_IsSpecialName
{
    public static void Main()
    {
        try
        {
            // Get the type handle of a specified class.
            Type myType = typeof(ViewTechnology);

            // Get the fields of the specified class.
            FieldInfo[] myField = myType.GetFields();

            Console.WriteLine("\nDisplaying fields that have SpecialName attributes:\n");
            for(int i = 0; i < myField.Length; i++)
            {
                // Determine whether or not each field is a special name.
                if(myField[i].IsSpecialName)
                {
                    Console.WriteLine("The field {0} has a SpecialName attribute.",
                        myField[i].Name);
                }
            }
        }
        catch(Exception e)
        {
            Console.WriteLine("Exception : {0} " , e.Message);
        }
    }
}
open System.ComponentModel.Design

try
    // Get the type handle of a specified class.
    let myType = typeof<ViewTechnology>

    // Get the fields of the specified class.
    let myFields = myType.GetFields()

    printfn $"\nDisplaying fields that have SpecialName attributes:\n"
    for field in myFields do
        // Determine whether or not each field is a special name.
        if field.IsSpecialName then
            printfn $"The field {field.Name} has a SpecialName attribute."
with e ->
    printfn $"Exception : {e.Message} "
Imports System.Reflection
Imports System.ComponentModel.Design

Class FieldInfo_IsSpecialName

    Public Shared Sub Main()
        Try
            ' Get the type handle of a specified class.
            Dim myType As Type = GetType(ViewTechnology)

            ' Get the fields of a specified class.
            Dim myField As FieldInfo() = myType.GetFields()

            Console.WriteLine(ControlChars.Cr + "Displaying fields that have SpecialName attributes:" + ControlChars.Cr)
            Dim i As Integer
            For i = 0 To myField.Length - 1
                ' Determine whether or not each field is a special name.
                If myField(i).IsSpecialName Then
                    Console.WriteLine("The field {0} has a SpecialName attribute.", myField(i).Name)
                End If
            Next i
        Catch e As Exception
            Console.WriteLine("Exception : {0} ", e.Message.ToString())
        End Try
    End Sub
End Class

설명

.NET 6 이전 버전에서 GetFields 메서드는 사전순 또는 선언 순서와 같은 특정 순서로 필드를 반환하지 않습니다. 해당 순서는 다르므로 코드는 필드가 반환되는 순서에 의존해서는 안 됩니다. 그러나 .NET 7부터는 어셈블리의 메타데이터 순서에 따라 순서가 결정적입니다.

다음 표에서는 형식을 반영할 때 메서드에서 반환되는 기본 클래스의 Get 멤버를 보여 줍니다.

멤버 형식 정적 비정적
생성자 No No
Field No Yes. 필드는 항상 이름과 서명을 기준으로 숨겨집니다.
Event 적용할 수 없음 일반적인 형식 시스템 규칙은 상속이 속성을 구현하는 메서드의 상속과 동일하다는 것입니다. 리플렉션은 속성을 이름별 숨기기 및 서명으로 처리합니다. 아래 참고 2를 참조하세요.
Method No Yes. 메서드(가상 및 가상이 아닌 메서드)는 이름으로 숨기기 또는 이름과 서명으로 숨기기가 가능합니다.
중첩 타입 No No
Property 적용할 수 없음 일반적인 형식 시스템 규칙은 상속이 속성을 구현하는 메서드의 상속과 동일하다는 것입니다. 리플렉션은 속성을 이름별 숨기기 및 서명으로 처리합니다. 아래 참고 2를 참조하세요.
  1. 이름별 및 서명에 의한 숨기기는 사용자 지정 한정자, 반환 형식, 매개 변수 형식, 센티넬 및 비관리 호출 규칙을 포함하여 서명의 모든 부분을 고려합니다. 이진 비교입니다.

  2. 리플렉션의 경우 속성과 이벤트는 이름 및 서명별로 숨겨집니다. 기본 클래스에 get 및 set 접근자가 모두 있는 속성이 있지만 파생 클래스에 get 접근자만 있는 경우 파생 클래스 속성은 기본 클래스 속성을 숨기며 기본 클래스의 setter에 액세스할 수 없습니다.

  3. 사용자 지정 특성은 공용 형식 시스템의 일부가 아닙니다.

현재 Type 가 생성된 제네릭 형식을 나타내는 경우 이 메서드는 형식 매개 변수가 적절한 형식 인수로 대체된 개체를 반환 FieldInfo 합니다.

현재 Type 제네릭 형식 또는 제네릭 메서드 정의에서 형식 매개 변수를 나타내는 경우 이 메서드는 클래스 제약 조건의 공용 필드를 검색합니다.

추가 정보

적용 대상

GetFields(BindingFlags)

파생 클래스에서 재정의되는 경우 지정된 바인딩 제약 조건을 사용하여 현재 Type대해 정의된 필드를 검색합니다.

public:
 abstract cli::array <System::Reflection::FieldInfo ^> ^ GetFields(System::Reflection::BindingFlags bindingAttr);
public abstract System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingAttr);
abstract member GetFields : System.Reflection.BindingFlags -> System.Reflection.FieldInfo[]
Public MustOverride Function GetFields (bindingAttr As BindingFlags) As FieldInfo()

매개 변수

bindingAttr
BindingFlags

검색을 수행하는 방법을 지정하는 열거형 값의 비트 조합입니다.

-또는-

Default 빈 배열을 반환합니다.

반품

지정된 바인딩 제약 조건과 일치하는 현재 Type 에 대해 정의된 모든 필드를 나타내는 개체의 배열 FieldInfo 입니다.

-또는-

현재Type에 대해 정의된 필드가 없거나 정의된 필드 중 바인딩 제약 조건과 일치하는 필드가 없는 경우 형식FieldInfo의 빈 배열입니다.

구현

예제

다음 예제에서는 메서드를 사용하는 방법을 보여 있습니다 GetFields(BindingFlags) .


using System;
using System.Reflection;

class AttributesSample
{
    public void Mymethod (int int1m, out string str2m, ref string str3m)
    {
        str2m = "in Mymethod";
    }

    public static int Main(string[] args)
    {
        Console.WriteLine ("Reflection.MethodBase.Attributes Sample");

        // Get the type.
        Type MyType = Type.GetType("AttributesSample");

        // Get the method Mymethod on the type.
        MethodBase Mymethodbase = MyType.GetMethod("Mymethod");

        // Display the method name.
        Console.WriteLine("Mymethodbase = " + Mymethodbase);

        // Get the MethodAttribute enumerated value.
        MethodAttributes Myattributes = Mymethodbase.Attributes;

        // Display the flags that are set.
        PrintAttributes(typeof(System.Reflection.MethodAttributes), (int) Myattributes);
        return 0;
    }

    public static void PrintAttributes(Type attribType, int iAttribValue)
    {
        if (!attribType.IsEnum)
        {
            Console.WriteLine("This type is not an enum.");
            return;
        }

        FieldInfo[] fields = attribType.GetFields(BindingFlags.Public | BindingFlags.Static);
        for (int i = 0; i < fields.Length; i++)
        {
            int fieldvalue = (int)fields[i].GetValue(null);
            if ((fieldvalue & iAttribValue) == fieldvalue)
            {
                Console.WriteLine(fields[i].Name);
            }
        }
    }
}
open System
open System.Reflection

type AttributesSample() =
    member _.Mymethod(int1m: int, str2m: string outref, str3m: string byref) =
        str2m <- "in Mymethod"

let printAttributes (attribType: Type) iAttribValue =
    if not attribType.IsEnum then
        printfn "This type is not an enum."
    else
        let fields = attribType.GetFields(BindingFlags.Public ||| BindingFlags.Static)
        for f in fields do
            let fieldvalue = f.GetValue null :?> int
            if fieldvalue &&& iAttribValue = fieldvalue then
                printfn $"{f.Name}"

printfn "Reflection.MethodBase.Attributes Sample"

// Get the type.
let MyType = Type.GetType "AttributesSample"

// Get the method Mymethod on the type.
let Mymethodbase = MyType.GetMethod "Mymethod"

// Display the method name.
printfn $"Mymethodbase = {Mymethodbase}"

// Get the MethodAttribute enumerated value.
let Myattributes = Mymethodbase.Attributes

// Display the flags that are set.
printAttributes typeof<MethodAttributes> (int Myattributes)
Imports System.Reflection

Class AttributesSample

    Public Sub Mymethod(ByVal int1m As Integer, ByRef str2m As String, ByRef str3m As String)
        str2m = "in Mymethod"
    End Sub

    Public Shared Function Main(ByVal args() As String) As Integer
        Console.WriteLine("Reflection.MethodBase.Attributes Sample")

        ' Get the type.
        Dim MyType As Type = Type.GetType("AttributesSample")

        ' Get the method Mymethod on the type.
        Dim Mymethodbase As MethodBase = MyType.GetMethod("Mymethod")

        ' Display the method name.
        Console.WriteLine("Mymethodbase = {0}.", Mymethodbase)

        ' Get the MethodAttribute enumerated value.
        Dim Myattributes As MethodAttributes = Mymethodbase.Attributes

        ' Display the flags that are set.
        PrintAttributes(GetType(System.Reflection.MethodAttributes), CInt(Myattributes))
        Return 0
    End Function 'Main

    Public Shared Sub PrintAttributes(ByVal attribType As Type, ByVal iAttribValue As Integer)
        If Not attribType.IsEnum Then
            Console.WriteLine("This type is not an enum.")
            Return
        End If
        Dim fields As FieldInfo() = attribType.GetFields((BindingFlags.Public Or BindingFlags.Static))
        Dim i As Integer
        For i = 0 To fields.Length - 1
            Dim fieldvalue As Integer = CType(fields(i).GetValue(Nothing), Int32)
            If (fieldvalue And iAttribValue) = fieldvalue Then
                Console.WriteLine(fields(i).Name)
            End If
        Next i
    End Sub
End Class

설명

오버로드가 GetFields(BindingFlags) 속성 정보를 bindingAttr 성공적으로 검색하려면 인수에 하나 이상의 BindingFlags.Instance 인수와 BindingFlags.Static하나 이상의 BindingFlags.NonPublicBindingFlags.Public인수가 포함되어야 합니다.

다음 BindingFlags 필터 플래그를 사용하여 검색에 포함할 필드를 정의할 수 있습니다.

  • 인스턴스 메서드를 포함하도록 지정 BindingFlags.Instance 합니다.

  • 정적 메서드를 포함하도록 지정 BindingFlags.Static 합니다.

  • 검색에 공용 필드를 포함하도록 지정 BindingFlags.Public 합니다.

  • 검색에 public이 아닌 필드(즉, 프라이빗, 내부 및 보호된 필드)를 포함하도록 지정 BindingFlags.NonPublic 합니다. 기본 클래스의 보호된 필드와 내부 필드만 반환됩니다. 기본 클래스의 private 필드는 반환되지 않습니다.

  • 위계에서 BindingFlags.FlattenHierarchypublic 정적 멤버를 포함하도록 protected을(를) 지정하세요. 상속된 클래스에서는 private 정적 멤버가 포함되지 않습니다.

  • BindingFlags.Default 배열을 반환하려면 단독으로 지정 PropertyInfo 합니다.

다음 BindingFlags 한정자 플래그를 사용하여 검색 작동 방식을 변경할 수 있습니다.

  • BindingFlags.DeclaredOnly 단순히 상속된 필드가 아니라 선언 Type된 필드만 검색합니다.

자세한 내용은 System.Reflection.BindingFlags을 참조하세요.

.NET 6 이전 버전에서 GetFields 메서드는 사전순 또는 선언 순서와 같은 특정 순서로 필드를 반환하지 않습니다. 해당 순서는 다르므로 코드는 필드가 반환되는 순서에 의존해서는 안 됩니다. 그러나 .NET 7부터는 어셈블리의 메타데이터 순서에 따라 순서가 결정적입니다.

현재 Type 가 생성된 제네릭 형식을 나타내는 경우 이 메서드는 형식 매개 변수가 적절한 형식 인수로 대체된 개체를 반환 FieldInfo 합니다.

현재 Type 제네릭 형식 또는 제네릭 메서드 정의에서 형식 매개 변수를 나타내는 경우 이 메서드는 클래스 제약 조건의 공용 필드를 검색합니다.

추가 정보

적용 대상