ObfuscationAttribute Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Instrui as ferramentas de ofuscação a realizar as ações especificadas para um montagem, 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)]
[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)]
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)>]
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)>]
type ObfuscationAttribute = class
inherit Attribute
Public NotInheritable Class ObfuscationAttribute
Inherits Attribute
- Herança
- Atributos
Exemplos
O seguinte exemplo de código mostra uma assembleia pública com dois tipos: Type1 e Type2. A assembleia está marcada para ofuscação com , ObfuscateAssemblyAttributeque marca a assembleia a ser tratada como pública (isto é, a AssemblyIsPrivate propriedade é false).
Type1 está marcado para ofuscação porque o conjunto está marcado para ofuscação. Um membro de Type1 é excluído da ofuscação, usando a Exclude propriedade.
Type2 é excluído da ofuscação, mas os seus membros estã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, porque o padrão para a Exclude propriedade é true. A ferramenta de ofuscação não deve remover o atributo após a ofuscação porque a StripAfterObfuscation propriedade é false. Todos os outros atributos neste exemplo de código são removidos após a ofuscação, porque a StripAfterObfuscation propriedade não é especificada e, por isso, passa por defeito a true.
O exemplo de código inclui código para mostrar os atributos e as suas propriedades. Também pode examinar os atributos abrindo a DLL com a 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
Observações
Os ObfuscationAttribute atributos and ObfuscateAssemblyAttribute permitem aos autores de assembly anotar os seus binários para que as ferramentas de ofuscação os processem corretamente com configuração externa mínima.
Importante
Aplicar este atributo não ofusca automaticamente a entidade de código a que o aplica. Aplicar o atributo é uma alternativa à criação de um ficheiro de configuração para a ferramenta de ofuscação. Ou seja, fornece apenas instruções para uma ferramenta de ofuscação. A Microsoft recomenda que os fornecedores de ferramentas de ofuscação sigam a semântica aqui descrita. No entanto, não há garantia de que uma determinada ferramenta siga as recomendações da Microsoft.
O ObfuscationAttribute atributo tem uma propriedade de cadeia Feature . As ferramentas de ofuscação podem mapear os valores da cadeia desta propriedade para as funcionalidades que implementam, preferencialmente usando um ficheiro de configuração XML ao qual os utilizadores possam aceder. Define ObfuscationAttribute duas sequências de características, "default" e "all". O "padrão" da string deve corresponder às funcionalidades de ofuscação padrão de uma ferramenta, e "todos" deve corresponder ao conjunto completo de funcionalidades de ofuscação suportadas por uma ferramenta. O valor padrão da Feature propriedade é "todos", permitindo o conjunto completo de funcionalidades de ofuscação.
Quando aplicado a um conjunto, ObfuscationAttribute também se aplica a todos os tipos dentro do conjunto. Se a ApplyToMembers propriedade não for especificada, ou for definida para true, o atributo aplica-se também a todos os membros.
ObfuscationAttribute não especifica se uma assembleia é pública ou privada. Para especificar se uma assembleia é pública ou privada, 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 for definida como true.
Quando aplicado a métodos, parâmetros, campos e propriedades, o atributo afeta apenas a entidade a que é aplicado.
Construtores
| Name | Description |
|---|---|
| ObfuscationAttribute() |
Inicializa uma nova instância da ObfuscationAttribute classe. |
Propriedades
| Name | Description |
|---|---|
| ApplyToMembers |
Recebe ou define um Boolean valor que indica se o atributo de um tipo se aplica aos membros do tipo. |
| Exclude |
Recebe ou define um Boolean valor que indica se a ferramenta de ofuscação deve excluir o tipo ou membro da ofuscação. |
| Feature |
Recebe ou define um valor de cadeia que é reconhecido pela ferramenta de ofuscação, e que especifica opções de processamento. |
| StripAfterObfuscation |
Recebe ou define um Boolean valor que indica se a ferramenta de ofuscação deve remover este atributo após o processamento. |
| TypeId |
Quando implementado numa classe derivada, obtém um identificador único para esta Attribute. (Herdado de Attribute) |
Métodos
| Name | Description |
|---|---|
| Equals(Object) |
Devolve um valor que indica se esta instância é igual a um objeto especificado. (Herdado de Attribute) |
| GetHashCode() |
Devolve o código de hash para esta instância. (Herdado de Attribute) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| IsDefaultAttribute() |
Quando sobrescrito numa classe derivada, indica se o valor desta instância é o valor padrão para a classe derivada. (Herdado de Attribute) |
| Match(Object) |
Quando sobrescrito numa classe derivada, devolve um valor que indica se esta instância é igual a um objeto especificado. (Herdado de Attribute) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |
Implementações de Interface Explícita
| Name | Description |
|---|---|
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de despacho. (Herdado de Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Recupera a informação de tipo de um objeto, que pode ser usada para obter a informação de tipo para uma interface. (Herdado de Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Recupera o número de interfaces de informações de tipo que um objeto fornece (0 ou 1). (Herdado de Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Proporciona acesso a propriedades e métodos expostos por um objeto. (Herdado de Attribute) |