-
[C#] AttributeC#/기초 2023. 7. 31. 13:13
MetaData 로 이해.
- 리플렉션
https://dlsenfl.tistory.com/entry/C-Reflection
[C#] Reflection
dlsenfl.tistory.com
사용자 지정 특성 만들기
- 아티클
- 2023. 03. 16.
- 기여자 1명
피드백메타데이터를 통해 특성의 정의를 빠르고 쉽게 식별할 수 있도록 해주는 Attribute로부터 직접적으로 또는 간접적으로 상속한 특성 클래스를 정의하여 사용자 지정 특성을 만들 수 있습니다. 형식을 작성한 프로그래머의 이름을 형식에 태그로 지정한다고 가정해봅시다. 사용자 지정 Author 특성 클래스를 아래와 같이 정의할 수 있습니다.
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct) ] public class AuthorAttribute : System.Attribute { private string Name; public double Version; public AuthorAttribute(string name) { Name = name; Version = 1.0; } }
클래스 이름 AuthorAttribute는 특성의 이름인 Author와 Attribute 접미사입니다. 에서 System.Attribute파생되므로 사용자 지정 특성 클래스입니다. 생성자의 매개 변수는 사용자 지정 특성의 위치 매개 변수입니다. 이 예제에서는 name이 위치 매개 변수입니다. 모든 public 읽기-쓰기 필드 또는 속성은 명명된 매개 변수입니다. 이 경우에는 version이 유일한 명명된 매개 변수입니다. 클래스 및 struct 선언에서만 Author 특성을 유효하게 설정하려면 AttributeUsage 특성을 사용해야 합니다.
이 새로운 특성은 다음과 같이 사용할 수 있습니다.
[Author("P. Ackerman", Version = 1.1)] class SampleClass { // P. Ackerman's code goes here... }
AttributeUsage에는 사용자 지정 특성을 한 번 또는 여러 번 사용하도록 설정하기 위해 사용하는 명명된 매개 변수인 AllowMultiple이 있습니다. 다음 코드 예제에서는 다중 사용 특성을 만듭니다.
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, AllowMultiple = true) // Multiuse attribute. ] public class AuthorAttribute : System.Attribute { string Name; public double Version; public AuthorAttribute(string name) { Name = name; // Default value. Version = 1.0; } public string GetName() => Name; }
다음 코드 예제에서는 같은 형식의 여러 특성이 한 클래스에 적용됩니다.
[Author("P. Ackerman"), Author("R. Koch", Version = 2.0)] public class ThirdClass { // ... }
사용자 지정 특성 만들기
Attribute 클래스에서 파생되는 특성 클래스를 정의하여 C#에서 사용자 지정 특성을 작성하는 방법에 대해 알아봅니다.
learn.microsoft.com
필드
All 32767 특성은 모든 애플리케이션 요소에 적용할 수 있습니다. Assembly 1 특성은 어셈블리에 적용할 수 있습니다. Class 4 특성은 클래스에 적용할 수 있습니다. Constructor 32 특성은 생성자에 적용할 수 있습니다. Delegate 4096 특성은 대리자에 적용할 수 있습니다. Enum 16 특성은 열거형에 적용할 수 있습니다. Event 512 특성은 이벤트에 적용할 수 있습니다. Field 256 특성은 필드에 적용할 수 있습니다. GenericParameter 16384 특성은 제네릭 매개 변수에 적용할 수 있습니다. 현재 이 특성은 C#, MSIL(Microsoft Intermediate language) 및 내보낸 코드에만 적용할 수 있습니다. Interface 1024 특성은 인터페이스에 적용할 수 있습니다. Method 64 특성은 메서드에 적용할 수 있습니다. Module 2 특성은 모듈에 적용할 수 있습니다. Module은 Visual Basic 표준 모듈이 아니라 이식 가능 파일(.dll 또는 .exe)을 나타냅니다. Parameter 2048 특성은 매개 변수에 적용할 수 있습니다. Property 128 특성은 속성에 적용할 수 있습니다. ReturnValue 8192 특성은 반환 값에 적용할 수 있습니다. Struct 8 특성은 구조체 즉, 값 형식에 적용할 수 있습니다.
https://learn.microsoft.com/ko-kr/dotnet/api/system.attributetargets?view=netframework-4.7.2
AttributeTargets 열거형 (System)
특성을 적용하는 데 유효한 애플리케이션 요소를 지정합니다.
learn.microsoft.com
Attribute 클래스
정의
네임스페이스:System어셈블리:System.Runtime.dll사용자 지정 특성에 대한 기본 클래스를 나타냅니다.
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple=false, Inherited=true)] public abstract class Attribute
상속
예제
다음 코드 예제에서는 Attribute의 사용을 보여 줍니다 .
객체의 메타데이터
using System; using System.Reflection; // An enumeration of animals. Start at 1 (0 = uninitialized). public enum Animal { // Pets. Dog = 1, Cat, Bird, } // A custom attribute to allow a target to have a pet. public class AnimalTypeAttribute : Attribute { // The constructor is called when the attribute is set. public AnimalTypeAttribute(Animal pet) { thePet = pet; } // Keep a variable internally ... protected Animal thePet; // .. and show a copy to the outside world. public Animal Pet { get { return thePet; } set { thePet = value; } } } // A test class where each method has its own pet. class AnimalTypeTestClass { [AnimalType(Animal.Dog)] public void DogMethod() {} [AnimalType(Animal.Cat)] public void CatMethod() {} [AnimalType(Animal.Bird)] public void BirdMethod() {} } class DemoClass { static void Main(string[] args) { AnimalTypeTestClass testClass = new AnimalTypeTestClass(); Type type = testClass.GetType(); // Iterate through all the methods of the class. foreach(MethodInfo mInfo in type.GetMethods()) { // Iterate through all the Attributes for each method. foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo)) { // Check for the AnimalType attribute. if (attr.GetType() == typeof(AnimalTypeAttribute)) Console.WriteLine( "Method {0} has a pet {1} attribute.", mInfo.Name, ((AnimalTypeAttribute)attr).Pet); } } } } /* * Output: * Method DogMethod has a pet Dog attribute. * Method CatMethod has a pet Cat attribute. * Method BirdMethod has a pet Bird attribute. */
[AttributeUsage(AttributeTargets.Method)] public class MyAttribute : Attribute { // . . . }
이 특성 정의는 다음과 같은 몇 가지 점을 보여 줍니다.
- 특성 클래스는 공용 클래스로 선언되어야 합니다.
- 특성 클래스의 이름은 규칙에 따라 Attribute로 끝납니다. 이 규칙을 반드시 적용할 필요는 없지만 가독성을 향상시키기 위해 사용하는 것이 좋습니다. 특성이 적용될 때 Attribute라는 단어를 포함시키지 않을 수도 있습니다.
- 모든 특성 클래스는 클래스에서 System.Attribute 직접 또는 간접적으로 상속해야 합니다.
사용자 지정 특성 예제
이 섹션에서는 이전 정보를 통합하고 코드 섹션의 작성자 정보를 문서화하는 특성을 디자인하는 방법을 보여 줍니다. 이 예제에서 사용된 특성에는 프로그래머의 이름 및 수준과 코드 검토 여부가 저장됩니다. 이 특성은 저장할 실제 값이 포함된 세 개의 private 변수를 사용합니다. 각 변수는 값을 가져오고 설정하는 public 속성으로 표시됩니다. 마지막으로 생성자는 다음 두 개의 필수 매개 변수로 정의됩니다.
[AttributeUsage(AttributeTargets.All)] public class DeveloperAttribute : Attribute { // Private fields. private string name; private string level; private bool reviewed; // This constructor defines two required parameters: name and level. public DeveloperAttribute(string name, string level) { this.name = name; this.level = level; this.reviewed = false; } // Define Name property. // This is a read-only attribute. public virtual string Name { get {return name;} } // Define Level property. // This is a read-only attribute. public virtual string Level { get {return level;} } // Define Reviewed property. // This is a read/write attribute. public virtual bool Reviewed { get {return reviewed;} set {reviewed = value;} } }
다음 방법 중 하나로 전체 이름 를 DeveloperAttribute사용하거나 약식 이름 를 Developer사용하여 이 특성을 적용할 수 있습니다.
[Developer("Joan Smith", "1")] -or- [Developer("Joan Smith", "1", Reviewed = true)]
https://learn.microsoft.com/ko-kr/dotnet/standard/attributes/writing-custom-attributes
사용자 지정 특성 작성
.NET에서 고유의 사용자 지정 특성을 디자인합니다. 사용자 지정 특성은 본래 System.Attribute에서 직접 또는 간접적으로 파생된 클래스입니다.
learn.microsoft.com
https://nowonbun.tistory.com/128
[C#] 31. 어트리뷰트(Attribute)를 사용하는 방법
안녕하세요. 명월입니다. 이 글은 C#에서 어트리뷰트(Attribute)를 사용하는 방법에 대한 글입니다. C#에서의 어트리뷰트(Attribute)란 클래스나 메소드에 메타데이터를 기록하는 데이터입니다. 여기
nowonbun.tistory.com
https://nomad-programmer.tistory.com/202
[Programming/C#] 어트리뷰트 (Attribute)
어트리뷰트(Attribute)는 코드에 대한 부가 정보를 기록하고 읽을 수 있는 기능이다. 어트리뷰트가 주석과 다른 점은 주석이 사람이 읽고 쓰는 정보라면, 어트리뷰트는 사람이 작성하고 컴퓨터가
nomad-programmer.tistory.com
728x90'C# > 기초' 카테고리의 다른 글
[C#] Reflection (0) 2023.07.31 [C#] 모듈정보 가져오기 (0) 2023.07.31 [C#] XML 파일 (0) 2023.07.05 [C#] Dictionary Append (0) 2023.07.05 [C#] Nuget.exe (0) 2023.06.26 댓글