46.11 특정 속성에 적용된 특성 읽어 오기
이번에는 리플렉션을 사용하여 특정 속성에 적용된 특성을 읽어 오는 방법을 알아보겠습니다. 다음 내용을 입력한 후 실행해 보세요.
특정 속성에 적용된 특성 읽어 오기: ReflectionGetProperty.cs
using System;
using System.Reflection;
namespace ReflectionGetProperty
{
class Person
{
[Obsolete] public string Name { get; set; }
}
class ReflectionGetProperty
{
static void Main()
{
//Name 속성의 정보 얻기
PropertyInfo pi = typeof(Person).GetProperty("Name");
//Name 속성에 적용된 특성 읽어 오기
object[] attributes = pi.GetCustomAttributes(false);
foreach (var attr in attributes)
{
//특성의 이름들 출력
Console.WriteLine("{0}", attr.GetType().Name);
}
}
}
}
실행 결과
ObsoleteAttribute
Type 개체의 GetProperty() 메서드로 특정 속성 정보를 얻고, 다시 GetCustomAttributes() 메서드로 특성 정보를 얻어 올 수 있습니다. 평상시 우리가 사용하던 코드보다는 좀 더 복잡하기에 닷넷 API 탐색기 등으로 각 메서드를 추가로 학습하길 권장합니다.