AssemblyBuilder.SetCustomAttribute AssemblyBuilder.SetCustomAttribute AssemblyBuilder.SetCustomAttribute AssemblyBuilder.SetCustomAttribute Method

Definición

Establece un atributo personalizado en este ensamblado.Sets a custom attribute on this assembly.

Sobrecargas

SetCustomAttribute(CustomAttributeBuilder) SetCustomAttribute(CustomAttributeBuilder) SetCustomAttribute(CustomAttributeBuilder) SetCustomAttribute(CustomAttributeBuilder)

Establezca un atributo personalizado en este ensamblado mediante un generador de atributos personalizados.Set a custom attribute on this assembly using a custom attribute builder.

SetCustomAttribute(ConstructorInfo, Byte[]) SetCustomAttribute(ConstructorInfo, Byte[]) SetCustomAttribute(ConstructorInfo, Byte[]) SetCustomAttribute(ConstructorInfo, Byte[])

Establezca un atributo personalizado en este ensamblado mediante el objeto binario especificado de atributo personalizado.Set a custom attribute on this assembly using a specified custom attribute blob.

SetCustomAttribute(CustomAttributeBuilder) SetCustomAttribute(CustomAttributeBuilder) SetCustomAttribute(CustomAttributeBuilder) SetCustomAttribute(CustomAttributeBuilder)

Establezca un atributo personalizado en este ensamblado mediante un generador de atributos personalizados.Set a custom attribute on this assembly using a custom attribute builder.

public:
 void SetCustomAttribute(System::Reflection::Emit::CustomAttributeBuilder ^ customBuilder);
public void SetCustomAttribute (System.Reflection.Emit.CustomAttributeBuilder customBuilder);
member this.SetCustomAttribute : System.Reflection.Emit.CustomAttributeBuilder -> unit
Public Sub SetCustomAttribute (customBuilder As CustomAttributeBuilder)

Parámetros

customBuilder
CustomAttributeBuilder CustomAttributeBuilder CustomAttributeBuilder CustomAttributeBuilder

Instancia de una clase del asistente para definir el atributo personalizado.An instance of a helper class to define the custom attribute.

Excepciones

El llamador no dispone del permiso requerido.The caller does not have the required permission.

Ejemplos

Ejemplo de código siguiente muestra el uso de SetCustomAttribute en AssemblyBuilder, mediante un CustomAttributeBuilder.The following code sample illustrates the use of SetCustomAttribute within AssemblyBuilder, using a CustomAttributeBuilder.

[AttributeUsage(AttributeTargets::All,AllowMultiple=false)]
public ref class MyAttribute: public Attribute
{
public:
   String^ s;
   int x;
   MyAttribute( String^ s, int x )
   {
      this->s = s;
      this->x = x;
   }
};

Type^ CreateCallee( AppDomain^ domain )
{
   AssemblyName^ myAssemblyName = gcnew AssemblyName;
   myAssemblyName->Name = "EmittedAssembly";
   AssemblyBuilder^ myAssembly = domain->DefineDynamicAssembly( myAssemblyName, AssemblyBuilderAccess::Run );
   Type^ myType = MyAttribute::typeid;
   array<Type^>^temp0 = {String::typeid,int::typeid};
   ConstructorInfo^ infoConstructor = myType->GetConstructor( temp0 );
   array<Object^>^temp1 = {"Hello",2};
   CustomAttributeBuilder^ attributeBuilder = gcnew CustomAttributeBuilder( infoConstructor,temp1 );
   myAssembly->SetCustomAttribute( attributeBuilder );
   ModuleBuilder^ myModule = myAssembly->DefineDynamicModule( "EmittedModule" );
   
   // Define a public class named "HelloWorld" in the assembly.
   TypeBuilder^ helloWorldClass = myModule->DefineType( "HelloWorld", TypeAttributes::Public );
   return (helloWorldClass->CreateType());
}

int main()
{
   Type^ customAttribute = CreateCallee( Thread::GetDomain() );
   array<Object^>^attributes = customAttribute->Assembly->GetCustomAttributes( true );
   Console::WriteLine( "MyAttribute custom attribute contains : " );
   for ( int index = 0; index < attributes->Length; index++ )
   {
      if ( dynamic_cast<MyAttribute^>(attributes[ index ]) )
      {
         Console::WriteLine( "s : {0}", (dynamic_cast<MyAttribute^>(attributes[ index ]))->s );
         Console::WriteLine( "x : {0}", (dynamic_cast<MyAttribute^>(attributes[ index ]))->x );
         break;
      }
   }
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class MyAttribute : Attribute
{
   public String s;
   public int x;

   public MyAttribute(String s, int x)
   {
      this.s = s;
      this.x = x;
   }
}

class MyApplication
{
   public static void Main()
   {
      Type customAttribute = CreateCallee(Thread.GetDomain());
      object[] attributes = customAttribute.Assembly.GetCustomAttributes(true);
      Console.WriteLine("MyAttribute custom attribute contains : ");
      for(int index=0; index < attributes.Length; index++)
      {
         if(attributes[index] is MyAttribute)
         {
            Console.WriteLine("s : " + ((MyAttribute)attributes[index]).s);
            Console.WriteLine("x : " + ((MyAttribute)attributes[index]).x);
            break;
         }
      }
   }


   private static Type CreateCallee(AppDomain domain)
   {
      AssemblyName myAssemblyName = new AssemblyName();
      myAssemblyName.Name = "EmittedAssembly";
      AssemblyBuilder myAssembly = domain.DefineDynamicAssembly(myAssemblyName,
         AssemblyBuilderAccess.Run);
      Type myType = typeof(MyAttribute);
      ConstructorInfo infoConstructor = myType.GetConstructor(new Type[2]{typeof(String), typeof(int)});
      CustomAttributeBuilder attributeBuilder =
         new CustomAttributeBuilder(infoConstructor, new object[2]{"Hello", 2});
      myAssembly.SetCustomAttribute(attributeBuilder);
      ModuleBuilder myModule = myAssembly.DefineDynamicModule("EmittedModule");
      // Define a public class named "HelloWorld" in the assembly.
      TypeBuilder helloWorldClass = myModule.DefineType("HelloWorld", TypeAttributes.Public);

      return(helloWorldClass.CreateType());
  }
}
<AttributeUsage(AttributeTargets.All, AllowMultiple := False)>  _
Public Class MyAttribute
   Inherits Attribute
   Public s As String
   Public x As Integer

   Public Sub New(s As String, x As Integer)
      Me.s = s
      Me.x = x
   End Sub 'New
End Class 'MyAttribute

Class MyApplication
   Public Shared Sub Main()
      Dim customAttribute As Type = CreateCallee(Thread.GetDomain())
      Dim attributes As Object() = customAttribute.Assembly.GetCustomAttributes(True)
      Console.WriteLine("MyAttribute custom attribute contains : ")
      Dim index As Integer
      For index = 0 To attributes.Length - 1
         If TypeOf attributes(index) Is MyAttribute Then
            Console.WriteLine("s : " + CType(attributes(index), MyAttribute).s)
            Console.WriteLine("x : " + CType(attributes(index), MyAttribute).x.ToString())
            Exit For
         End If
      Next index
   End Sub 'Main

   Private Shared Function CreateCallee(domain As AppDomain) As Type
      Dim myAssemblyName As New AssemblyName()
      myAssemblyName.Name = "EmittedAssembly"
      Dim myAssembly As AssemblyBuilder = _
                     domain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run)
      Dim myType As Type = GetType(MyAttribute)
      Dim infoConstructor As ConstructorInfo = _
                     myType.GetConstructor(New Type(1) {GetType(String), GetType(Integer)})
      Dim attributeBuilder As New CustomAttributeBuilder(infoConstructor, New Object(1) {"Hello", 2})
      myAssembly.SetCustomAttribute(attributeBuilder)
      Dim myModule As ModuleBuilder = myAssembly.DefineDynamicModule("EmittedModule")
      ' Define a public class named "HelloWorld" in the assembly.
      Dim helloWorldClass As TypeBuilder = myModule.DefineType("HelloWorld", TypeAttributes.Public)
      Return helloWorldClass.CreateType()
   End Function 'CreateCallee
End Class 'MyApplication

Comentarios

Nota

SetCustomAttribute no se puede usar para establecer los atributos de seguridad declarativa.SetCustomAttribute cannot be used to set declarative security attributes. Use una de las sobrecargas de DefineDynamicAssembly que toma requerido, opcional y no los permisos.Use one of the overloads of DefineDynamicAssembly that takes required, optional, and refused permissions.

Nota

A partir de la .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, ya no requiere este miembro ReflectionPermission con el ReflectionPermissionFlag.ReflectionEmit marca.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this member no longer requires ReflectionPermission with the ReflectionPermissionFlag.ReflectionEmit flag. (Consulte problemas de seguridad en Reflection emiten.) Para utilizar esta funcionalidad, la aplicación debe utilizar .NET Framework 3,5.NET Framework 3.5 o posterior como destino.(See Security Issues in Reflection Emit.) To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Seguridad

ReflectionPermission
Cuando se invoca en tiempo de ejecución a través de mecanismos como InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]).when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeración asociada: MemberAccess.Associated enumeration: MemberAccess.

SetCustomAttribute(ConstructorInfo, Byte[]) SetCustomAttribute(ConstructorInfo, Byte[]) SetCustomAttribute(ConstructorInfo, Byte[]) SetCustomAttribute(ConstructorInfo, Byte[])

Establezca un atributo personalizado en este ensamblado mediante el objeto binario especificado de atributo personalizado.Set a custom attribute on this assembly using a specified custom attribute blob.

public:
 void SetCustomAttribute(System::Reflection::ConstructorInfo ^ con, cli::array <System::Byte> ^ binaryAttribute);
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute (System.Reflection.ConstructorInfo con, byte[] binaryAttribute);
member this.SetCustomAttribute : System.Reflection.ConstructorInfo * byte[] -> unit
Public Sub SetCustomAttribute (con As ConstructorInfo, binaryAttribute As Byte())

Parámetros

con
ConstructorInfo ConstructorInfo ConstructorInfo ConstructorInfo

Constructor para el atributo personalizado.The constructor for the custom attribute.

binaryAttribute
Byte[]

Blob de bytes que representa los atributos.A byte blob representing the attributes.

Excepciones

con o binaryAttribute es null.con or binaryAttribute is null.

El llamador no dispone del permiso requerido.The caller does not have the required permission.

con no es un objeto RuntimeConstructorInfo.con is not a RuntimeConstructorInfo object.

Ejemplos

Ejemplo de código siguiente muestra el uso de SetCustomAttribute para asociar un atributo personalizado a un ensamblado generado dinámicamente.The following code sample illustrates the use of SetCustomAttribute to attach a custom attribute to a dynamically generated assembly.

using namespace System;
using namespace System::Threading;
using namespace System::Reflection;
using namespace System::Reflection::Emit;

[AttributeUsage(AttributeTargets::All,AllowMultiple=false)]
public ref class MyAttribute: public Attribute
{
public:
   bool s;
   MyAttribute( bool s )
   {
      this->s = s;
   }
};

Type^ CreateCallee( AppDomain^ domain )
{
   AssemblyName^ myAssemblyName = gcnew AssemblyName;
   myAssemblyName->Name = "EmittedAssembly";
   AssemblyBuilder^ myAssembly = domain->DefineDynamicAssembly( myAssemblyName, AssemblyBuilderAccess::Run );
   Type^ myType = MyAttribute::typeid;
   array<Type^>^temp0 = {bool::typeid};
   ConstructorInfo^ infoConstructor = myType->GetConstructor( temp0 );
   array<Byte>^temp1 = {01,00,01};
   myAssembly->SetCustomAttribute( infoConstructor, temp1 );
   ModuleBuilder^ myModule = myAssembly->DefineDynamicModule( "EmittedModule" );

   // Define a public class named "HelloWorld" in the assembly.
   TypeBuilder^ helloWorldClass = myModule->DefineType( "HelloWorld", TypeAttributes::Public );
   return (helloWorldClass->CreateType());
}

int main()
{
   Type^ customAttribute = CreateCallee( Thread::GetDomain() );
   array<Object^>^attributes = customAttribute->Assembly->GetCustomAttributes( true );
   Console::WriteLine( "MyAttribute custom attribute contains : " );
   for ( int index = 0; index < attributes->Length; index++ )
   {
      if ( dynamic_cast<MyAttribute^>(attributes[ index ]) )
      {
         Console::WriteLine( "s : {0}", (dynamic_cast<MyAttribute^>(attributes[ index ]))->s );
         break;
      }
   }
}
using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;


[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class MyAttribute : Attribute
{
   public bool s;

   public MyAttribute(bool s)
   {
      this.s = s;
   }
}

class MyApplication
{
   public static void Main()
   {
      Type customAttribute = CreateCallee(Thread.GetDomain());
      object[] attributes = customAttribute.Assembly.GetCustomAttributes(true);
      Console.WriteLine("MyAttribute custom attribute contains : ");
      for(int index=0; index < attributes.Length; index++)
      {
         if(attributes[index] is MyAttribute)
         {
            Console.WriteLine("s : " + ((MyAttribute)attributes[index]).s);
            break;
         }
      }
   }

   private static Type CreateCallee(AppDomain domain)
   {
      AssemblyName myAssemblyName = new AssemblyName();
      myAssemblyName.Name = "EmittedAssembly";
      AssemblyBuilder myAssembly = domain.DefineDynamicAssembly(myAssemblyName,
         AssemblyBuilderAccess.Run);
      Type myType = typeof(MyAttribute);
      ConstructorInfo infoConstructor = myType.GetConstructor(new Type[]{typeof(bool)});
      myAssembly.SetCustomAttribute(infoConstructor, new byte[]{01,00,01});
      ModuleBuilder myModule = myAssembly.DefineDynamicModule("EmittedModule");
      // Define a public class named "HelloWorld" in the assembly.
      TypeBuilder helloWorldClass = myModule.DefineType("HelloWorld", TypeAttributes.Public);

      return(helloWorldClass.CreateType());
  }
}
Imports System
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit


<AttributeUsage(AttributeTargets.All, AllowMultiple := False)>  _
Public Class MyAttribute
   Inherits Attribute
   Public s As Boolean
   
   Public Sub New(s As Boolean)
      Me.s = s
   End Sub 'New
End Class 'MyAttribute

Class MyApplication
   
   Public Shared Sub Main()
      Dim customAttribute As Type = CreateCallee(Thread.GetDomain())
      Dim attributes As Object() = customAttribute.Assembly.GetCustomAttributes(True)
      Console.WriteLine("MyAttribute custom attribute contains : ")
      Dim index As Integer
      For index = 0 To attributes.Length - 1
         If TypeOf attributes(index) Is MyAttribute Then
            Console.WriteLine("s : " + CType(attributes(index), MyAttribute).s.ToString())
            Exit For
         End If
      Next index
   End Sub 'Main
   
   Private Shared Function CreateCallee(domain As AppDomain) As Type
      Dim myAssemblyName As New AssemblyName()
      myAssemblyName.Name = "EmittedAssembly"
      Dim myAssembly As AssemblyBuilder = domain.DefineDynamicAssembly(myAssemblyName, _
                                                            AssemblyBuilderAccess.Run)
      Dim myType As Type = GetType(MyAttribute)
      Dim infoConstructor As ConstructorInfo = myType.GetConstructor(New Type() {GetType(Boolean)})
      myAssembly.SetCustomAttribute(infoConstructor, New Byte() {01, 00, 01})
      Dim myModule As ModuleBuilder = myAssembly.DefineDynamicModule("EmittedModule")
      ' Define a public class named "HelloWorld" in the assembly.
      Dim helloWorldClass As TypeBuilder = myModule.DefineType("HelloWorld", TypeAttributes.Public)
      
      Return helloWorldClass.CreateType()
   End Function 'CreateCallee
End Class 'MyApplication

Comentarios

Vea la especificación de metadatos en la documentación de ECMA Partition II para obtener más información sobre cómo dar formato a binaryAttribute.See the metadata specification in the ECMA Partition II documentation for details on how to format binaryAttribute. La documentación está disponible en línea; vea ECMA C# and Common Language Infrastructure Standards (Estándares de ECMA C# y Common Language Infrastructure) en MSDN y Standard ECMA-335 - Common Language Infrastructure (CLI) (Estándar ECMA-335: Common Language Infrastructure [CLI]) en el sitio web de Ecma International.The documentation is available online; see ECMA C# and Common Language Infrastructure Standards on MSDN and Standard ECMA-335 - Common Language Infrastructure (CLI) on the Ecma International Web site.

RuntimeConstructorInfo es un tipo especial generado por el sistema.RuntimeConstructorInfo is a special type generated by the system. Deriva el ConstructorInfo clase y cualquier ConstructorInfo objeto obtenido mediante reflexión es realmente una instancia de RuntimeConstructorInfo.It derives from the ConstructorInfo class, and any ConstructorInfo object you obtain through reflection is actually an instance of RuntimeConstructorInfo.

Nota

SetCustomAttribute no se puede usar para establecer los atributos de seguridad declarativa.SetCustomAttribute cannot be used to set declarative security attributes. Use una de las sobrecargas de DefineDynamicAssembly que toma requerido, opcional y no los permisos.Use one of the overloads of DefineDynamicAssembly that takes required, optional, and refused permissions.

Nota

A partir de la .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, ya no requiere este miembro ReflectionPermission con el ReflectionPermissionFlag.ReflectionEmit marca.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this member no longer requires ReflectionPermission with the ReflectionPermissionFlag.ReflectionEmit flag. (Consulte problemas de seguridad en Reflection emiten.) Para utilizar esta funcionalidad, la aplicación debe utilizar .NET Framework 3,5.NET Framework 3.5 o posterior como destino.(See Security Issues in Reflection Emit.) To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.

Seguridad

ReflectionPermission
Cuando se invoca en tiempo de ejecución a través de mecanismos como InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]).when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumeración asociada: MemberAccess.Associated enumeration: MemberAccess.

Se aplica a