728x90
속성은 직접적으로 코드 실행에 영향을 주지는 않지만, 리플렉션(Reflection) 을 사용하면 속성이 적용된 멤버를 확인할 수 있습니다.
class Important : System.Attribute
{
string message;
public Important(string message) { this.message = message; }
}
class Monster
{
[Important("very")]
public int hp;
protected int attack;
private float speed;
}
리플렉션으로 속성 확인하기
using System;
using System.Reflection;
class Program
{
static void Main()
{
Type type = typeof(Monster);
foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
var attribute = (Important)Attribute.GetCustomAttribute(field, typeof(Important));
if (attribute != null)
{
Console.WriteLine($"{field.Name} 필드는 중요한 속성입니다!");
}
}
}
}
728x90
'VisualStudio > C#' 카테고리의 다른 글
[C#서버][방법] 배치(bat)파일 사용 방법 Main(string[] args) args 인자 값 만들기 (0) | 2022.11.01 |
---|---|
[C#서버][개념] 임계영역(크리티컬섹션)상호배제 - Moniter, lock (0) | 2022.10.26 |
C#[방법] 리플랙션(Reflection) Class 속성 출력 방법 (0) | 2022.10.11 |
[C#] 제네릭 형식 제약 조건(Where) (0) | 2022.10.05 |
[C#] C# 7.0 에서 편리해진 out 파라미터 사용방법 (0) | 2022.09.20 |