ObfuscationAttribute Classe

Definição

Instrui as ferramentas de ofuscação a realizar as ações especificadas para um assembly, tipo ou membro.

public ref class ObfuscationAttribute sealed : Attribute
[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
public sealed class ObfuscationAttribute : Attribute
[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)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ObfuscationAttribute : Attribute
[<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)>]
type ObfuscationAttribute = class
    inherit Attribute
type ObfuscationAttribute = class
    inherit Attribute
[<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)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ObfuscationAttribute = class
    inherit Attribute
Public NotInheritable Class ObfuscationAttribute
Inherits Attribute
Herança
ObfuscationAttribute
Atributos

Exemplos

O exemplo de código a seguir mostra um assembly público com dois tipos: Type1 e Type2. O assembly é marcado para ofuscação com o ObfuscateAssemblyAttribute, que marca o assembly a ser tratado como público (ou seja, a AssemblyIsPrivate propriedade é false).

Type1 é marcado como ofuscação porque o assembly está marcado para ofuscação. Um membro é Type1 excluído da ofuscação, usando a Exclude propriedade.

Type2 é excluído da ofuscação, mas seus membros são marcados para ofuscação porque a ApplyToMembers propriedade é false.

O MethodA método de Type2 é marcado com o valor "default" da Feature propriedade. É necessário especificar false para a Exclude propriedade evitar a exclusão MethodA da ofuscação, pois o padrão para a Exclude propriedade é true. A ferramenta ofuscação não deve remover o atributo após ofuscação porque a StripAfterObfuscation propriedade é false. Todos os outros atributos neste exemplo de código são removidos após ofuscação, pois a StripAfterObfuscation propriedade não é especificada e, portanto, é padrão .true

O exemplo de código inclui código para exibir os atributos e suas propriedades. Você também pode examinar os atributos abrindo a DLL com o 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

Comentários

Os ObfuscationAttribute atributos e ObfuscateAssemblyAttribute os atributos permitem aos autores do assembly anotar seus binários para que as ferramentas de ofuscação possam processá-los corretamente com configuração externa mínima.

Importante

A aplicação desse atributo não ofusca automaticamente a entidade de código à qual você a aplica. A aplicação do atributo é uma alternativa à criação de um arquivo de configuração para a ferramenta ofuscação. Ou seja, ele apenas fornece instruções para uma ferramenta de ofuscação. A Microsoft recomenda que os fornecedores de ferramentas de ofuscação sigam a semântica descrita aqui. No entanto, não há garantia de que uma ferramenta específica siga as recomendações da Microsoft.

O ObfuscationAttribute atributo tem uma propriedade de cadeia de caracteres Feature . As ferramentas de ofuscação podem mapear os valores de cadeia de caracteres dessa propriedade para os recursos implementados, preferencialmente usando um arquivo de configuração XML que os usuários podem acessar. A ObfuscationAttribute definição de duas cadeias de caracteres de recurso, "default" e "all". A cadeia de caracteres "padrão" deve ser mapeada para os recursos de ofuscação padrão de uma ferramenta e "todos" devem ser mapeados para o conjunto completo de recursos de ofuscação com suporte de uma ferramenta. O valor padrão da Feature propriedade é "todos", habilitando o conjunto completo de recursos de ofuscação.

Quando aplicado a um assembly, ObfuscationAttribute também se aplica a todos os tipos dentro do assembly. Se a ApplyToMembers propriedade não for especificada ou estiver definida como true, o atributo também se aplicará a todos os membros. ObfuscationAttribute não especifica se um assembly é público ou privado. Para especificar se um assembly é público ou privado, use o ObfuscateAssemblyAttribute atributo.

Quando aplicado a classes e estruturas, ObfuscationAttribute também se aplica a todos os membros do tipo se a ApplyToMembers propriedade não for especificada ou estiver definida como true.

Quando aplicado a métodos, parâmetros, campos e propriedades, o atributo afeta apenas a entidade à qual ela é aplicada.

Construtores

ObfuscationAttribute()

Inicializa uma nova instância da classe ObfuscationAttribute.

Propriedades

ApplyToMembers

Obtém ou define um valor Boolean que indica se o atributo de tipo deve ser aplicado aos membros do tipo.

Exclude

Obtém ou define um valor Boolean que indica se a ferramenta de ofuscação deve excluir o tipo ou membro da ofuscação.

Feature

Obtém ou define um valor de cadeia de caracteres que é reconhecido pela ferramenta de ocultamento e que especifica as opções de processamento.

StripAfterObfuscation

Obtém ou define um valor Boolean que indica se a ferramenta de ocultamento deve remover esse atributo após o processamento.

TypeId

Quando implementado em uma classe derivada, obtém um identificador exclusivo para este Attribute.

(Herdado de Attribute)

Métodos

Equals(Object)

Retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
GetHashCode()

Retorna o código hash para a instância.

(Herdado de Attribute)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
IsDefaultAttribute()

Quando substituído em uma classe derivada, indica se o valor dessa instância é o valor padrão para a classe derivada.

(Herdado de Attribute)
Match(Object)

Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Implantações explícitas de interface

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

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.

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

Recupera as informações de tipo para um objeto, que pode ser usado para obter as informações de tipo para uma interface.

(Herdado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).

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

Fornece acesso a propriedades e métodos expostos por um objeto.

(Herdado de Attribute)

Aplica-se a

Confira também