GeneratedCodeAttribute Класс

Определение

Определяет код, созданный средством. Этот класс не наследуется.

public ref class GeneratedCodeAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple=false, Inherited=false)]
public sealed class GeneratedCodeAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.All, AllowMultiple=false, Inherited=false)>]
type GeneratedCodeAttribute = class
    inherit Attribute
Public NotInheritable Class GeneratedCodeAttribute
Inherits Attribute
Наследование
GeneratedCodeAttribute
Атрибуты

Примеры

В следующем примере кода показано использование класса для идентификации GeneratedCodeAttribute кода, созданного компьютером.

#using <System.dll>
#using <System.Xml.dll>

using namespace System;
using namespace System::CodeDom;
using namespace System::CodeDom::Compiler;

int main()
{
    // Declare a new type called Class1.
    CodeTypeDeclaration^ class1 = gcnew CodeTypeDeclaration("Class1");

    // Declare a new generated code attribute
    GeneratedCodeAttribute^ generatedCodeAttribute =
        gcnew GeneratedCodeAttribute("SampleCodeGenerator", "2.0.0.0");

    // Use the generated code attribute members in the attribute declaration
    CodeAttributeDeclaration^ codeAttrDecl =
        gcnew CodeAttributeDeclaration(generatedCodeAttribute->GetType()->Name,
            gcnew CodeAttributeArgument(
                gcnew CodePrimitiveExpression(generatedCodeAttribute->Tool)),
            gcnew CodeAttributeArgument(
                gcnew CodePrimitiveExpression(generatedCodeAttribute->Version)));
    class1->CustomAttributes->Add(codeAttrDecl);

    // Create a C# code provider
    CodeDomProvider^ provider = CodeDomProvider::CreateProvider("CSharp");

    // Generate code and send the output to the console
    provider->GenerateCodeFromType(class1, Console::Out, gcnew CodeGeneratorOptions());
}

// The CPP code generator produces the following source code for the preceeding example code:
//
// [GeneratedCodeAttribute("SampleCodeGenerator", "2.0.0.0")]
// public class Class1 {
// }
using System;
using System.CodeDom;
using System.CodeDom.Compiler;

public class CodeGenExample
{
    static void Main()
    {
        // Declare a new type called Class1.
        CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1");

        // Declare a new generated code attribute
        GeneratedCodeAttribute generatedCodeAttribute =
            new GeneratedCodeAttribute("SampleCodeGenerator", "2.0.0.0");

        // Use the generated code attribute members in the attribute declaration
        CodeAttributeDeclaration codeAttrDecl =
            new CodeAttributeDeclaration(generatedCodeAttribute.GetType().Name,
                new CodeAttributeArgument(
                    new CodePrimitiveExpression(generatedCodeAttribute.Tool)),
                new CodeAttributeArgument(
                    new CodePrimitiveExpression(generatedCodeAttribute.Version)));
        class1.CustomAttributes.Add(codeAttrDecl);

        // Create a C# code provider
        CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

        // Generate code and send the output to the console
        provider.GenerateCodeFromType(class1, Console.Out, new CodeGeneratorOptions());
    }
}

// The C# code generator produces the following source code for the preceeding example code:
//
// [GeneratedCodeAttribute("SampleCodeGenerator", "2.0.0.0")]
// public class Class1 {
// }
Imports System.CodeDom
Imports System.CodeDom.Compiler

Public Class CodeGenExample

    Shared Sub Main
        ' Declare a new type called Class1.
        Dim class1 as New CodeTypeDeclaration("Class1")

        ' Declare a new generated code attribute
        Dim generatedCodeAttribute As _
            New GeneratedCodeAttribute("SampleCodeGenerator", "2.0.0.0")

        ' Use the generated code attribute members in the attribute declaration
        Dim  codeAttrDecl As _
            New CodeAttributeDeclaration(generatedCodeAttribute.GetType().Name,
                New CodeAttributeArgument(
                    New CodePrimitiveExpression(generatedCodeAttribute.Tool)),
                New CodeAttributeArgument(
                    New CodePrimitiveExpression(generatedCodeAttribute.Version)))
        class1.CustomAttributes.Add(codeAttrDecl)

        ' Create a Visual Basic code provider
        Dim provider As CodeDomProvider = CodeDomProvider.CreateProvider("VisualBasic")

        ' Generate code and send the output to the console
        provider.GenerateCodeFromType(class1, Console.Out, New CodeGeneratorOptions())
    End Sub

End Class

' The Visual Basic code generator produces the following source code for the preceeding example code:
'
' <GeneratedCodeAttribute("SampleCodeGenerator", "2.0.0.0")>  _
' Public Class Class1
' End Class

Комментарии

Класс GeneratedCodeAttribute можно использовать средствами анализа кода для идентификации созданного компьютером кода, а также для предоставления анализа на основе средства и версии средства, создающего код.

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

GeneratedCodeAttribute(String, String)

Инициализирует новый экземпляр класса GeneratedCodeAttribute с указанием имени и версии средства, сгенерировавшего код.

Свойства

Tool

Получает имя средства, сгенерировавшего код.

TypeId

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

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

Получает версию средства, сгенерировавшего код.

Методы

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)

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