ObfuscationAttribute Clase

Definición

Indica a las herramientas de ofuscación que tomen las acciones especificadas para un ensamblado, tipo o miembro.Instructs obfuscation tools to take the specified actions for an assembly, type, or member.

public ref class ObfuscationAttribute sealed : Attribute
[System.Runtime.InteropServices.ComVisible(true)]
[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Delegate | System.AttributeTargets.Enum | System.AttributeTargets.Event | System.AttributeTargets.Field | System.AttributeTargets.Interface | System.AttributeTargets.Method | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)]
public sealed class ObfuscationAttribute : Attribute
type ObfuscationAttribute = class
    inherit Attribute
Public NotInheritable Class ObfuscationAttribute
Inherits Attribute
Herencia
ObfuscationAttribute
Atributos

Ejemplos

En el ejemplo de código siguiente se muestra un ensamblado público con dos tipos: Type1 y Type2.The following code example shows a public assembly with two types: Type1 and Type2. El ensamblado está marcado para ofuscación con el ObfuscateAssemblyAttribute, que marca el ensamblado que se va a tratar como público (es decir, se falsela propiedad AssemblyIsPrivate).The assembly is marked for obfuscation with the ObfuscateAssemblyAttribute, which marks the assembly to be treated as public (that is, the AssemblyIsPrivate property is false).

Type1 está marcado para ofuscación porque el ensamblado está marcado para ofuscación.Type1 is marked for obfuscation because the assembly is marked for obfuscation. Un miembro de Type1 se excluye de la ofuscación mediante la propiedad Exclude.One member of Type1 is excluded from obfuscation, using the Exclude property.

Type2 se excluye de la ofuscación, pero sus miembros se marcan para ofuscación porque la propiedad ApplyToMembers está false.Type2 is excluded from obfuscation, but its members are marked for obfuscation because the ApplyToMembers property is false.

El método MethodA de Type2 se marca con el valor "default" para la propiedad Feature.The MethodA method of Type2 is marked with the value "default" for the Feature property. Es necesario especificar false para la propiedad Exclude para evitar excluir MethodA de ofuscación, ya que el valor predeterminado de la propiedad Exclude es true.It is necessary to specify false for the Exclude property to avoid excluding MethodA from obfuscation, because the default for the Exclude property is true. La herramienta de ofuscación no debe quitar el atributo después de ofuscación porque la propiedad StripAfterObfuscation se false.The obfuscation tool should not strip the attribute after obfuscation because the StripAfterObfuscation property is false. Todos los demás atributos de este ejemplo de código se quitan después de la ofuscación, porque no se especifica la propiedad StripAfterObfuscation y, por tanto, el valor predeterminado es true.All the other attributes in this code example are stripped after obfuscation, because the StripAfterObfuscation property is not specified, and therefore defaults to true.

En el ejemplo de código se incluye código para mostrar los atributos y sus propiedades.The code example includes code to display the attributes and their properties. También puede examinar los atributos abriendo el archivo DLL con Ildasm. exe (desensamblador de IL).You can also examine the attributes by opening the DLL with the Ildasm.exe (IL Disassembler).

using System;
using System.Reflection;

// Mark this public assembly for obfuscation.
[assembly:ObfuscateAssemblyAttribute(false)]

// This class is marked for obfuscation, because the assembly
// is marked.
public class Type1
{

    // Exclude this method from obfuscation. The default value
    // of the Exclude property is true, so it is not necessary
    // to specify Exclude=True, although spelling it out makes
    // your intent clearer.
    [ObfuscationAttribute(Exclude=true)]
    public void MethodA() {}

    // This member is marked for obfuscation because the class
    // is marked.
    public void MethodB() {}
}

// Exclude this type from obfuscation, but do not apply that
// exclusion to members. The default value of the Exclude 
// property is true, so it is not necessary to specify 
// Exclude=true, although spelling it out makes your intent 
// clearer.
[ObfuscationAttribute(Exclude=true, ApplyToMembers=false)]
public class Type2
{

    // The exclusion of the type is not applied to its members,
    // however in order to mark the member with the "default" 
    // feature it is necessary to specify Exclude=false,
    // because the default value of Exclude is true. The tool
    // should not strip this attribute after obfuscation.
    [ObfuscationAttribute(Exclude=false, Feature="default", 
        StripAfterObfuscation=false)]
    public void MethodA() {}

    // This member is marked for obfuscation, because the 
    // exclusion of the type is not applied to its members.
    public void MethodB() {}

}

// This class only exists to provide an entry point for the
// assembly and to display the attribute values.
internal class Test
{

    public static void Main()
    {

        // Display the ObfuscateAssemblyAttribute properties
        // for the assembly.        
        Assembly assem = typeof(Test).Assembly;
        object[] assemAttrs = assem.GetCustomAttributes(
            typeof(ObfuscateAssemblyAttribute), false);

        foreach( Attribute a in assemAttrs )
        {
            ShowObfuscateAssembly((ObfuscateAssemblyAttribute) a);
        }

        // Display the ObfuscationAttribute properties for each
        // type that is visible to users of the assembly.
        foreach( Type t in assem.GetTypes() )
        {
            if (t.IsVisible)
            {
                object[] tAttrs = t.GetCustomAttributes(
                    typeof(ObfuscationAttribute), false);

                foreach( Attribute a in tAttrs )
                {
                    ShowObfuscation(((ObfuscationAttribute) a),
                        t.Name);
                }

                // Display the ObfuscationAttribute properties
                // for each member in the type.
                foreach( MemberInfo m in t.GetMembers() )
                {
                    object[] mAttrs = m.GetCustomAttributes(
                        typeof(ObfuscationAttribute), false);

                    foreach( Attribute a in mAttrs )
                    {
                        ShowObfuscation(((ObfuscationAttribute) a), 
                            t.Name + "." + m.Name);
                    }
                }
            }
        }
    }

    private static void ShowObfuscateAssembly(
        ObfuscateAssemblyAttribute ob)
    {
        Console.WriteLine("\r\nObfuscateAssemblyAttribute properties:");
        Console.WriteLine("   AssemblyIsPrivate: {0}", 
            ob.AssemblyIsPrivate);
        Console.WriteLine("   StripAfterObfuscation: {0}",
            ob.StripAfterObfuscation);
    }

    private static void ShowObfuscation(
        ObfuscationAttribute ob, string target)
    {
        Console.WriteLine("\r\nObfuscationAttribute properties for: {0}",
            target);
        Console.WriteLine("   Exclude: {0}", ob.Exclude);
        Console.WriteLine("   Feature: {0}", ob.Feature);
        Console.WriteLine("   StripAfterObfuscation: {0}",
            ob.StripAfterObfuscation);
        Console.WriteLine("   ApplyToMembers: {0}", ob.ApplyToMembers);
    }
}

/* This code example produces the following output:

ObfuscateAssemblyAttribute properties:
   AssemblyIsPrivate: False
   StripAfterObfuscation: True

ObfuscationAttribute properties for: Type1.MethodA
   Exclude: True
   Feature: all
   StripAfterObfuscation: True
   ApplyToMembers: True

ObfuscationAttribute properties for: Type2
   Exclude: True
   Feature: all
   StripAfterObfuscation: True
   ApplyToMembers: False

ObfuscationAttribute properties for: Type2.MethodA
   Exclude: False
   Feature: default
   StripAfterObfuscation: False
   ApplyToMembers: True
 */
Imports System.Reflection

' Mark this public assembly for obfuscation.
<Assembly: ObfuscateAssemblyAttribute(False)>

' This class is marked for obfuscation, because the assembly
' is marked.
Public Class Type1

    ' Exclude this method from obfuscation. The default value
    ' of the Exclude property is True, so it is not necessary
    ' to specify Exclude:=True, although spelling it out makes
    ' your intent clearer.
    <ObfuscationAttribute(Exclude:=True)> _
    Public Sub MethodA()
    End Sub

    ' This member is marked for obfuscation because the class
    ' is marked.
    Public Sub MethodB()
    End Sub

End Class

' Exclude this type from obfuscation, but do not apply that
' exclusion to members. The default value of the Exclude 
' property is True, so it is not necessary to specify 
' Exclude:=True, although spelling it out makes your intent 
' clearer.
<ObfuscationAttribute(Exclude:=True, ApplyToMembers:=False)> _
Public Class Type2

    ' The exclusion of the type is not applied to its members,
    ' however in order to mark the member with the "default" 
    ' feature it is necessary to specify Exclude:=False,
    ' because the default value of Exclude is True. The tool
    ' should not strip this attribute after obfuscation.
    <ObfuscationAttribute(Exclude:=False, _
        Feature:="default", StripAfterObfuscation:=False)> _
    Public Sub MethodA()
    End Sub

    ' This member is marked for obfuscation, because the 
    ' exclusion of the type is not applied to its members.
    Public Sub MethodB()
    End Sub

End Class

' This class only exists to provide an entry point for the
' assembly and to display the attribute values.
Friend Class Test

    Public Shared Sub Main()

        ' Display the ObfuscateAssemblyAttribute properties
        ' for the assembly.        
        Dim assem As Assembly =GetType(Test).Assembly
        Dim assemAttrs() As Object = _
            assem.GetCustomAttributes( _
                GetType(ObfuscateAssemblyAttribute), _
                False)

        For Each a As Attribute In assemAttrs
            ShowObfuscateAssembly(CType(a, ObfuscateAssemblyAttribute))
        Next

        ' Display the ObfuscationAttribute properties for each
        ' type that is visible to users of the assembly.
        For Each t As Type In assem.GetTypes()
            If t.IsVisible Then
                Dim tAttrs() As Object = _
                    t.GetCustomAttributes( _
                        GetType(ObfuscationAttribute), _
                        False)

                For Each a As Attribute In tAttrs
                    ShowObfuscation(CType(a, ObfuscationAttribute), _
                        t.Name)
                Next

                ' Display the ObfuscationAttribute properties
                ' for each member in the type.
                For Each m As MemberInfo In t.GetMembers()
                    Dim mAttrs() As Object = _
                        m.GetCustomAttributes( _
                            GetType(ObfuscationAttribute), _
                            False)

                    For Each a As Attribute In mAttrs
                        ShowObfuscation(CType(a, ObfuscationAttribute), _
                            t.Name & "." & m.Name)
                    Next
                Next
            End If
        Next
    End Sub

    Private Shared Sub ShowObfuscateAssembly( _
        ByVal ob As ObfuscateAssemblyAttribute)
        
        Console.WriteLine(vbCrLf & "ObfuscateAssemblyAttribute properties:")
        Console.WriteLine("   AssemblyIsPrivate: " _
            & ob.AssemblyIsPrivate)
        Console.WriteLine("   StripAfterObfuscation: " _
            & ob.StripAfterObfuscation)

    End Sub

    Private Shared Sub ShowObfuscation( _
        ByVal ob As ObfuscationAttribute, _
        ByVal target As String)
        
        Console.WriteLine(vbCrLf _
            & "ObfuscationAttribute properties for: " _
            & target)
        Console.WriteLine("   Exclude: " & ob.Exclude)
        Console.WriteLine("   Feature: " & ob.Feature)
        Console.WriteLine("   StripAfterObfuscation: " _
            & ob.StripAfterObfuscation)
        Console.WriteLine("   ApplyToMembers: " & ob.ApplyToMembers)

    End Sub
End Class

' This code example produces the following output:
'
'ObfuscateAssemblyAttribute properties:
'   AssemblyIsPrivate: False
'   StripAfterObfuscation: True
'
'ObfuscationAttribute properties for: Type1.MethodA
'   Exclude: True
'   Feature: all
'   StripAfterObfuscation: True
'   ApplyToMembers: True
'
'ObfuscationAttribute properties for: Type2
'   Exclude: True
'   Feature: all
'   StripAfterObfuscation: True
'   ApplyToMembers: False
'
'ObfuscationAttribute properties for: Type2.MethodA
'   Exclude: False
'   Feature: default
'   StripAfterObfuscation: False
'   ApplyToMembers: True

Comentarios

Los atributos ObfuscationAttribute y ObfuscateAssemblyAttribute permiten a los autores de ensamblados anotar sus archivos binarios para que las herramientas de ofuscación puedan procesarlos correctamente con la configuración externa mínima.The ObfuscationAttribute and ObfuscateAssemblyAttribute attributes allow assembly authors to annotate their binaries so that obfuscation tools can process them correctly with minimal external configuration.

Importante

Al aplicar este atributo no se ofusca automáticamente la entidad de código a la que se aplica.Applying this attribute does not automatically obfuscate the code entity to which you apply it. Aplicar el atributo es una alternativa a la creación de un archivo de configuración para la herramienta de ofuscación.Applying the attribute is an alternative to creating a configuration file for the obfuscation tool. Es decir, simplemente proporciona instrucciones para una herramienta de ofuscación.That is, it merely provides instructions for an obfuscation tool. Microsoft recomienda que los proveedores de herramientas de ofuscación sigan la semántica que se describe aquí.Microsoft recommends that vendors of obfuscation tools follow the semantics described here. Sin embargo, no hay ninguna garantía de que una herramienta determinada siga las recomendaciones de Microsoft.However, there is no guarantee that a particular tool follows Microsoft recommendations.

El atributo ObfuscationAttribute tiene una cadena Feature propiedad.The ObfuscationAttribute attribute has a string Feature property. Las herramientas de ofuscación pueden asignar los valores de cadena de esta propiedad a las características que implementan, preferiblemente mediante un archivo de configuración XML al que pueden tener acceso los usuarios.Obfuscation tools can map the string values of this property to features they implement, preferably by using an XML configuration file that users can access. El ObfuscationAttribute define dos cadenas de características, "default" y "All".The ObfuscationAttribute defines two feature strings, "default" and "all". La cadena "default" debe estar asignada a las características de ofuscación predeterminadas de una herramienta y "All" debe asignarse al conjunto completo de características de ofuscación admitidas por una herramienta.The string "default" should map to the default obfuscation features of a tool, and "all" should map to the complete set of obfuscation features supported by a tool. El valor predeterminado de la propiedad Feature es "All", lo que habilita el conjunto completo de características de ofuscación.The default value of the Feature property is "all", enabling the complete set of obfuscation features.

Cuando se aplica a un ensamblado, ObfuscationAttribute también se aplica a todos los tipos del ensamblado.When applied to an assembly, ObfuscationAttribute also applies to all types within the assembly. Si no se especifica la propiedad ApplyToMembers o se establece en true, el atributo se aplica también a todos los miembros.If the ApplyToMembers property is not specified, or is set to true, the attribute applies to all members as well. ObfuscationAttribute no especifica si un ensamblado es público o privado.ObfuscationAttribute does not specify whether an assembly is public or private. Para especificar si un ensamblado es público o privado, use el atributo ObfuscateAssemblyAttribute.To specify whether an assembly is public or private, use the ObfuscateAssemblyAttribute attribute.

Cuando se aplica a clases y estructuras, ObfuscationAttribute también se aplica a todos los miembros del tipo si no se especifica la propiedad ApplyToMembers o se establece en true.When applied to classes and structures, ObfuscationAttribute also applies to all members of the type if the ApplyToMembers property is not specified, or is set to true.

Cuando se aplica a métodos, parámetros, campos y propiedades, el atributo solo afecta a la entidad a la que se aplica.When applied to methods, parameters, fields, and properties, the attribute affects only the entity to which it is applied.

Constructores

ObfuscationAttribute()

Inicializa una nueva instancia de la clase ObfuscationAttribute.Initializes a new instance of the ObfuscationAttribute class.

Propiedades

ApplyToMembers

Obtiene o establece un valor Boolean que indica si el atributo de un tipo se ha de aplicar a los miembros del tipo.Gets or sets a Boolean value indicating whether the attribute of a type is to apply to the members of the type.

Exclude

Obtiene o establece un valor Boolean que indica si la herramienta de ofuscación debe excluir de ofuscación el tipo o el miembro.Gets or sets a Boolean value indicating whether the obfuscation tool should exclude the type or member from obfuscation.

Feature

Obtiene o establece un valor de cadena que es reconocido por la herramienta de ofuscación y que especifica opciones de procesamiento.Gets or sets a string value that is recognized by the obfuscation tool, and which specifies processing options.

StripAfterObfuscation

Obtiene o establece un valor Boolean que indica si la herramienta de ofuscación debe quitar este atributo tras el procesamiento.Gets or sets a Boolean value indicating whether the obfuscation tool should remove this attribute after processing.

TypeId

Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute.When implemented in a derived class, gets a unique identifier for this Attribute.

(Heredado de Attribute)

Métodos

Equals(Object)

Devuelve un valor que indica si esta instancia es igual que un objeto especificado.Returns a value that indicates whether this instance is equal to a specified object.

(Heredado de Attribute)
GetHashCode()

Devuelve el código hash de esta instancia.Returns the hash code for this instance.

(Heredado de Attribute)
GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Heredado de Object)
IsDefaultAttribute()

Si se reemplaza en una clase derivada, indica si el valor de esta instancia es el valor predeterminado de la clase derivada.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Heredado de Attribute)
Match(Object)

Cuando se invalida en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Heredado de Attribute)
MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Heredado de Object)
ToString()

Devuelve un valor de tipo string que representa el objeto actual.Returns a string that represents the current object.

(Heredado de Object)

Implementaciones de interfaz explícitas

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.Maps a set of names to a corresponding set of dispatch identifiers.

(Heredado de Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Obtiene la información de tipos de un objeto, que puede utilizarse para obtener la información de tipos de una interfaz.Retrieves the type information for an object, which can be used to get the type information for an interface.

(Heredado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Heredado de Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acceso a las propiedades y los métodos expuestos por un objeto.Provides access to properties and methods exposed by an object.

(Heredado de Attribute)

Se aplica a

Consulte también: