CustomAttributeBuilder Class
Represents a custom attribute, enabling you to build and associate custom attributes with dynamic types, methods, and members at runtime. This class is part of the Reflection.Emit API, allowing for advanced meta-programming scenarios.
Constructors
-
CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs)
Initializes a new instance of the
CustomAttributeBuilder
class with the specified constructor and constructor arguments. -
CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs, FieldInfo[] namedFields, Object[] fieldValues)
Initializes a new instance of the
CustomAttributeBuilder
class with the specified constructor, constructor arguments, named fields, and their corresponding values. -
CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs, PropertyInfo[] namedProperties, Object[] propertyValues)
Initializes a new instance of the
CustomAttributeBuilder
class with the specified constructor, constructor arguments, named properties, and their corresponding values. -
CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs, PropertyInfo[] namedProperties, Object[] propertyValues, FieldInfo[] namedFields, Object[] fieldValues)
Initializes a new instance of the
CustomAttributeBuilder
class with the specified constructor, constructor arguments, named properties, their values, named fields, and their values.
Methods
-
GetConstructorArguments()
Retrieves the arguments passed to the constructor of the custom attribute.
-
GetNamedArguments()
Retrieves the named arguments (fields and properties) associated with the custom attribute.
Remarks
The CustomAttributeBuilder
class is a crucial component for dynamically creating custom attributes in .NET. It allows you to define the structure and values of an attribute at runtime, which can then be applied to dynamically generated types, methods, or other members. This is particularly useful in scenarios like:
- Code Generation: Creating dynamic types with specific metadata.
- Metaprogramming: Building powerful tools that analyze and manipulate code.
- Aspect-Oriented Programming: Implementing cross-cutting concerns dynamically.
When creating a CustomAttributeBuilder
, you typically provide:
- A
ConstructorInfo
object representing the attribute's constructor. - An array of objects for the constructor's arguments.
- Optionally, arrays of
FieldInfo
andPropertyInfo
objects along with their corresponding values to set named fields and properties of the attribute.
The resulting CustomAttributeBuilder
can then be passed to methods on TypeBuilder
, MethodBuilder
, or other relevant emission classes to associate the custom attribute with the generated code element.
Example
using System;
using System.Reflection;
using System.Reflection.Emit;
public class DynamicAttributeUsage
{
public static void Main(string[] args)
{
// Define a simple custom attribute for demonstration
// This would typically be a pre-defined attribute class
// For this example, we'll simulate it by using an existing type with attributes
// Create an in-memory assembly and module
AssemblyName assemblyName = new AssemblyName("MyDynamicAssembly");
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
// Define a dynamic type
TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType");
// Get the constructor of the AttributeUsage attribute
ConstructorInfo attributeUsageConstructor = typeof(System.AttributeUsageAttribute).GetConstructor(new Type[] { typeof(AttributeTargets) });
// Create arguments for the AttributeUsage constructor
object[] attributeUsageArgs = { AttributeTargets.Class | AttributeTargets.Method };
// Create a CustomAttributeBuilder for AttributeUsage
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(
attributeUsageConstructor,
attributeUsageArgs);
// Apply the custom attribute to the dynamic type
typeBuilder.SetCustomAttribute(attributeBuilder);
// Create a dynamic method
MethodBuilder methodBuilder = typeBuilder.DefineMethod(
"MyDynamicMethod",
MethodAttributes.Public | MethodAttributes.Static,
typeof(void),
null);
// Get the constructor of the Obsolete attribute
ConstructorInfo obsoleteConstructor = typeof(System.ObsoleteAttribute).GetConstructor(new Type[] { typeof(string) });
// Create arguments for the Obsolete constructor
object[] obsoleteArgs = { "This method is obsolete." };
// Create a CustomAttributeBuilder for Obsolete
CustomAttributeBuilder obsoleteAttributeBuilder = new CustomAttributeBuilder(
obsoleteConstructor,
obsoleteArgs);
// Apply the custom attribute to the dynamic method
methodBuilder.SetCustomAttribute(obsoleteAttributeBuilder);
// Create the type
Type dynamicType = typeBuilder.CreateType();
Console.WriteLine($"Dynamic type '{dynamicType.Name}' created with AttributeUsage applied.");
MethodInfo dynamicMethod = dynamicType.GetMethod("MyDynamicMethod");
Console.WriteLine($"Dynamic method '{dynamicMethod.Name}' created with Obsolete attribute applied.");
// You can further inspect attributes using reflection
var attrs = dynamicType.GetCustomAttributes(typeof(System.AttributeUsageAttribute), false);
if (attrs.Length > 0)
{
var usageAttr = (System.AttributeUsageAttribute)attrs[0];
Console.WriteLine($"AttributeUsage on {dynamicType.Name}: Targets = {usageAttr.ValidOn}");
}
var methodAttrs = dynamicMethod.GetCustomAttributes(typeof(System.ObsoleteAttribute), false);
if (methodAttrs.Length > 0)
{
var obsoleteAttr = (System.ObsoleteAttribute)methodAttrs[0];
Console.WriteLine($"Obsolete on {dynamicMethod.Name}: Message = '{obsoleteAttr.Message}'");
}
}
}