In C#, custom attributes (also known as custom metadata or annotations) allow you to attach additional information or metadata to various program entities such as classes, methods, properties, and more. These attributes are then accessible at runtime using reflection, which allows you to inspect and manipulate the behavior of your code based on this metadata. Custom attributes are commonly used in scenarios like serialization, validation, and code documentation.
Here's an example of creating a custom attribute in C#:
using System;
// Define a custom attribute called "AuthorAttribute" that can be applied to classes and methods.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorAttribute : Attribute
{
public string Name { get; }
public AuthorAttribute(string name)
{
Name = name;
}
}
// Apply the custom attribute to a class and a method.
[Author("John Doe")]
class MyClass
{
[Author("Alice Smith")]
public void MyMethod()
{
Console.WriteLine("Hello, world!");
}
}
class Program
{
static void Main()
{
// Use reflection to access and display the custom attribute values.
Type myClassType = typeof(MyClass);
object[] classAttributes = myClassType.GetCustomAttributes(typeof(AuthorAttribute), false);
if (classAttributes.Length > 0)
{
AuthorAttribute classAuthorAttribute = (AuthorAttribute)classAttributes[0];
Console.WriteLine($"Author of MyClass: {classAuthorAttribute.Name}");
}
var myMethod = typeof(MyClass).GetMethod("MyMethod");
object[] methodAttributes = myMethod.GetCustomAttributes(typeof(AuthorAttribute), false);
if (methodAttributes.Length > 0)
{
AuthorAttribute methodAuthorAttribute = (AuthorAttribute)methodAttributes[0];
Console.WriteLine($"Author of MyMethod: {methodAuthorAttribute.Name}");
}
}
}
In this example:
- We define a custom attribute called AuthorAttribute that takes a string parameter in its constructor.
- We apply this custom attribute to both a class (MyClass) and a method (MyMethod) using square brackets.
- In the Main method, we use reflection to access the custom attribute values for the MyClass and MyMethod. We retrieve the attribute objects and extract the Name property to display the author's name.
When you run this code, it will output:
Author of MyClass: John Doe
Author of MyMethod: Alice Smith
This demonstrates how custom attributes can be used to attach additional information to program entities and retrieve that information at runtime using reflection.
No comments:
Post a Comment