ObfuscationAttribute Класс

Определение

Указывает средствам запутывания, что следует предпринять заданные действия для сборки, типа или члена.

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
Наследование
ObfuscationAttribute
Атрибуты

Примеры

В следующем примере кода показана общедоступная сборка с двумя типами: Type1 и Type2. Сборка помечена для маскировки с ObfuscateAssemblyAttributeпомощью , который помечает сборку как общедоступную (то есть свойство AssemblyIsPrivate имеет значение false).

Type1 помечен для маскировки, так как сборка помечена как обфускация. Один член Type1 исключается из обфускации с помощью Exclude свойства .

Type2 исключается из маскировки, но его члены помечаются для маскировки, так как ApplyToMembers свойство имеет значение false.

Метод MethodA помечается Type2 значением "default"Feature свойства . Необходимо указать false для Exclude свойства , чтобы избежать исключения MethodA из маскирования, так как значение по умолчанию для Exclude свойства — true. Средство обфускации не должно удалять атрибут после обфускации, StripAfterObfuscation так как свойство имеет значение false. Все остальные атрибуты в этом примере кода удаляются после маскировки, так как StripAfterObfuscation свойство не указано и по умолчанию имеет значение true.

Пример кода включает код для отображения атрибутов и их свойств. Вы также можете проверить атрибуты, открыв библиотеку DLL с Ildasm.exe (дизассемблер IL).

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

Комментарии

ObfuscationAttribute Атрибуты и ObfuscateAssemblyAttribute позволяют авторам сборок добавлять заметки к двоичным файлам, чтобы средства маскирования могли правильно обрабатывать их с минимальной внешней конфигурацией.

Важно!

Применение этого атрибута не приводит к автоматическому запутыванию сущности кода, к которой он применяется. Применение атрибута является альтернативой созданию файла конфигурации для средства маскирования. То есть он просто предоставляет инструкции для средства маскации. Майкрософт рекомендует поставщикам средств маскирования следовать описанной здесь семантике. Однако нет никакой гарантии, что конкретный инструмент следует Майкрософт рекомендациям.

Атрибут ObfuscationAttribute имеет строковое Feature свойство. Средства обфускации могут сопоставлять строковые значения этого свойства с возможностями, которые они реализуют, предпочтительно с помощью XML-файла конфигурации, к которому пользователи могут получить доступ. Определяет ObfuscationAttribute две строки признаков: default и all. Строка "default" должна сопоставляться с функциями маскировки по умолчанию средства, а "all" — с полным набором функций обфускации, поддерживаемых средством. Значение свойства по умолчанию Feature — all, что позволяет использовать полный набор функций маскации.

При применении к сборке ObfuscationAttribute также применяется ко всем типам в сборке. ApplyToMembers Если свойство не указано или имеет значение true, атрибут также применяется ко всем членам. ObfuscationAttribute не указывает, является ли сборка общедоступной или частной. Чтобы указать, является ли сборка общедоступной или частной ObfuscateAssemblyAttribute , используйте атрибут .

При применении к классам и структурам также применяется ко всем членам типа, ObfuscationAttribute если ApplyToMembers свойство не указано или имеет значение true.

При применении к методам, параметрам, полям и свойствам атрибут влияет только на сущность, к которой он применяется.

Конструкторы

ObfuscationAttribute()

Инициализирует новый экземпляр класса ObfuscationAttribute.

Свойства

ApplyToMembers

Возвращает или задает значение Boolean, которое указывает, должен ли атрибут определенного типа быть применен к членам этого типа.

Exclude

Возвращает или задает значение Boolean, указывающее, должно ли средство запутывания исключить тип или член из операции запутывания.

Feature

Возвращает или задает строковое значение, которое распознается средством запутывания и определяет параметры обработки.

StripAfterObfuscation

Возвращает или задает значение Boolean, указывающее, должно и средство запутывания удалить данный атрибут по окончании его обработки.

TypeId

В случае реализации в производном классе возвращает уникальный идентификатор для этого атрибута Attribute.

(Унаследовано от Attribute)

Методы

Equals(Object)

Возвращает значение, показывающее, равен ли экземпляр указанному объекту.

(Унаследовано от Attribute)
GetHashCode()

Возвращает хэш-код данного экземпляра.

(Унаследовано от Attribute)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
IsDefaultAttribute()

При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса.

(Унаследовано от Attribute)
Match(Object)

При переопределении в производном классе возвращает значение, указывающее, является ли этот экземпляр равным заданному объекту.

(Унаследовано от Attribute)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Явные реализации интерфейса

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

Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации.

(Унаследовано от Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Возвращает сведения о типе объекта, которые можно использовать для получения сведений о типе интерфейса.

(Унаследовано от Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1).

(Унаследовано от Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Предоставляет доступ к открытым свойствам и методам объекта.

(Унаследовано от Attribute)

Применяется к

См. также раздел