Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# Type.GetProperties() 메서드 완벽 정리 – 타입의 속성 정보 조회 방법

C#에서 Type.GetProperties() 메서드는 현재 Type 객체가 가지고 있는 모든 속성(Property) 정보를 조회할 때 사용하는 리플렉션(Reflection) API입니다. 이 메서드를 활용하면 클래스나 구조체에 선언된 public 속성들을 런타임에 동적으로 확인할 수 있습니다.

문법(Syntax)

Type.GetProperties() 메서드는 두 가지 오버로드 형태로 제공됩니다.

public System.Reflection.PropertyInfo[] GetProperties ();
public abstract System.Reflection.PropertyInfo[] GetProperties (System.Reflection.BindingFlags bindingAttr);

매개변수 bindingAttr는 검색 방식을 지정하는 열거형 값들의 비트 조합(bitwise combination)입니다. 예를 들어, public 속성만 조회할지, 비public 속성까지 포함할지 등을 결정할 수 있습니다. 매개변수 없이 호출하면 기본적으로 public 인스턴스 및 정적(static) 속성이 반환됩니다.

예제 1: System.Type의 속성 조회

다음은 System.Type 자체의 속성 목록을 가져오는 예제입니다.

using System;
using System.Reflection;
public class Demo {
    public static void Main(){
        Type type = typeof(System.Type);
        PropertyInfo[] info = type.GetProperties();
        Console.WriteLine("Properties... ");
        for (int i = 0; i < info.Length; i++)
            Console.WriteLine(" {0}", info[i].ToString());
    }
}

실행 결과

위 코드를 실행하면 다음과 같이 System.Type에 정의된 속성들이 출력됩니다.

Properties...
System.Reflection.MemberTypes MemberType
System.Type DeclaringType
System.Reflection.MethodBase DeclaringMethod
System.Type ReflectedType
System.Runtime.InteropServices.StructLayoutAttribute StructLayoutAttribute
System.Guid GUID
System.Reflection.Binder DefaultBinder
System.Reflection.Module Module
System.Reflection.Assembly Assembly
System.RuntimeTypeHandle TypeHandle
System.String FullName
System.String Namespace
System.String AssemblyQualifiedName
System.Type BaseType
System.Reflection.ConstructorInfo TypeInitializer
Boolean IsNested
System.Reflection.TypeAttributes Attributes
System.Reflection.GenericParameterAttributes GenericParameterAttributes
Boolean IsVisible
Boolean IsNotPublic
Boolean IsPublic
Boolean IsNestedPublic
Boolean IsNestedPrivate
Boolean IsNestedFamily
Boolean IsNestedAssembly
Boolean IsNestedFamANDAssem
Boolean IsNestedFamORAssem
Boolean IsAutoLayout
Boolean IsLayoutSequential
Boolean IsExplicitLayout
Boolean IsClass
Boolean IsInterface
Boolean IsValueType
Boolean IsAbstract
Boolean IsSealed
Boolean IsEnum
Boolean IsSpecialName
Boolean IsImport
Boolean IsSerializable
Boolean IsAnsiClass
Boolean IsUnicodeClass
Boolean IsAutoClass
Boolean IsArray
Boolean IsGenericType
Boolean IsGenericTypeDefinition
Boolean IsConstructedGenericType
Boolean IsGenericParameter
Int32 GenericParameterPosition
Boolean ContainsGenericParameters
Boolean IsByRef
Boolean IsPointer
Boolean IsPrimitive
Boolean IsCOMObject
Boolean HasElementType
Boolean IsContextful
Boolean IsMarshalByRef
System.Type[] GenericTypeArguments
Boolean IsSecurityCritical
Boolean IsSecuritySafeCritical
Boolean IsSecurityTransparent
System.Type UnderlyingSystemType
System.String Name
System.Collections.Generic.IEnumerable`1[System.Reflection.CustomAttributeData] CustomAttributes
Int32 MetadataToken

예제 2: string 타입의 속성 개수와 목록 조회

이번에는 string 타입에 적용해 보겠습니다. 아래 예제에서는 속성의 총 개수와 함께 각 속성의 이름을 출력합니다.

using System;
using System.Reflection;
public class Demo {
    public static void Main(){
        Type type = typeof(string);
        PropertyInfo[] info = type.GetProperties();
        Console.WriteLine("Count of Properties = "+info.Length);
        Console.WriteLine("Properties... ");
        for (int i = 0; i < info.Length; i++)
            Console.WriteLine(" {0}", info[i].ToString());
    }
}

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Count of Properties = 2
Properties...
Char Chars [Int32]
Int32 Length

정리

Type.GetProperties() 메서드는 리플렉션을 통해 타입의 속성 정보를 동적으로 탐색할 수 있는 강력한 도구입니다. 반환되는 각 요소는 PropertyInfo 객체로, 속성 이름뿐 아니라 데이터 타입, getter/setter 접근 여부 등 다양한 메타데이터를 제공합니다. 매개변수 없이 호출하면 public 속성만 조회되며, BindingFlags를 지정하면 private 속성 등 더 세밀한 검색 조건을 설정할 수 있습니다.