Language/C#

[C#] Reflection - MemberInfo/FieldInfo / PropertyInfo

리네엔 2024. 10. 30. 21:04

MemberInfo

  • 클래스의 맴버 정보
using System;
using System.Reflection;

public class Item  
{  
    public string? ID;  
    public string? Name { get; set; }  
    public string? Description { get; set; }  
}

public class FieldInfoClass  
{

    public static void Main()
    {
        Type itemClassType = typeof(Item);
        MemberInfo[] info = itemClassType.GetMembers();
        foreach (var member in info)
        {
            Console.WriteLine($"Member Name: {member.Name}, Member Type: {member.MemberType}");
        }
    }
}
  • Get Memebers로 맴버들을 가져옴
Member Name: get\_Name, Member Type: Method  
Member Name: set\_Name, Member Type: Method  
Member Name: get\_Description, Member Type: Method  
Member Name: set\_Description, Member Type: Method  
Member Name: GetType, Member Type: Method  
Member Name: ToString, Member Type: Method  
Member Name: Equals, Member Type: Method  
Member Name: GetHashCode, Member Type: Method  
Member Name: .ctor, Member Type: Constructor  
Member Name: Name, Member Type: Property  
Member Name: Description, Member Type: Property  
Member Name: ID, Member Type: Field

FieldInfo

  • 클래스의 필드 정보
    public static void Main()
    {
        Type itemClassType = typeof(Item);
        FieldInfo[] info = itemClassType.GetFields();
        foreach (var member in info)
        {
            Console.WriteLine($"Field Name: {member.Name}, Field Type: {member.FieldType}");
        }
    }
Field Name: ID, Field Type: System.String

Property Info

  • 클래스의 프로퍼티 정보
    public static void Main()
    {
        Type itemClassType = typeof(Item);
        PropertyInfo[] info = itemClassType.GetProperties();
        foreach (var member in info)
        {
            Console.WriteLine($"Field Name: {member.Name}, Field Type: {member.PropertyType}");
        }
    }
Field Name: Name, Field Type: System.String
Field Name: Description, Field Type: System.String

그래서 이걸 어디다 쓰는데요?

excel,csv 등의 텍스트 데이터로부터 클래스의 데이터를 불러올 때 사용 가능!
예시1

'Language > C#' 카테고리의 다른 글

[C#] Skip  (0) 2024.11.06
[C#] Const와 Readonly  (0) 2024.10.14
[C#] Serialization & Deserializaton  (0) 2024.10.14
[C#] String Builder  (0) 2024.10.14
[C#] 클래스 상속, 추상클래스, 인터페이스  (0) 2024.10.14