[C#] Get Field Info, 필드 이름 가져오는 방법 (타입과 리플렉션을 통해 멤버 변수 접근하기)

C#에서 클래스의 특정 필드의 이름을 가져오려면 Type 객체의 GetFields 속성(리플렉션)을 사용할 수 있습니다. 여러 필드를 추가하고 다양한 경우를 다룬 예시로 살펴보도록 할게요.

필드 이름 가져오기 예시 코드

using System;
using System.Reflection;

public class MyClass
{
    // 공개 필드
    public int PublicField;
    public string AnotherPublicField;

    // 비공개 필드
    private double PrivateField;
    private bool HiddenFlag = true;

    // 상수 필드
    public const string ConstantField = "ConstantValue";
    
    // 정적 필드
    public static float StaticField = 10.5f;

    // 읽기 전용 필드
    public readonly char ReadOnlyField = 'R';
}

class Program
{
    static void Main(string[] args)
    {
        // MyClass의 타입 정보를 얻습니다.
        Type type = typeof(MyClass);

        // 모든 필드를 가져옵니다.
        FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

        // 필드 이름을 출력합니다.
        foreach (FieldInfo field in fields)
        {
            Console.WriteLine("필드 이름: " + field.Name);
        }
    }
}

설명

  1. BindingFlags: 필드의 접근 수준에 따라 BindingFlags를 조합하여 사용했습니다.
    • BindingFlags.Public: 공개 필드를 가져옵니다.
    • BindingFlags.NonPublic: 비공개 필드를 가져옵니다.
    • BindingFlags.Instance: 인스턴스 필드를 가져옵니다.
    • BindingFlags.Static: 정적 필드를 가져옵니다.
  2. 필드 추가: 다양한 필드 타입(정적, 읽기 전용, 상수, 공개/비공개)을 포함하여 출력하도록 해보았어요.
  3. FieldInfo[]: 클래스에 정의된 모든 필드 정보를 배열로 가져온 후, Name 속성을 통해 필드 이름을 출력합니다.

출력 예시

필드 이름: PublicField
필드 이름: AnotherPublicField
필드 이름: PrivateField
필드 이름: HiddenFlag
필드 이름: ReadOnlyField
필드 이름: StaticField
필드 이름: ConstantField

이 코드는 클래스 MyClass 내 모든 필드의 이름을 출력합니다~ 공개 필드뿐만 아니라 비공개 필드도 BindingFlags를 사용하여 가져올 수 있답니다.

댓글 쓰기
가져가실 때, 출처 표시 부탁드려요! 감사합니다. 💗