CodeAttributeArgument Класс

Определение

Представляет аргумент, используемый в объявлении атрибута метаданных.

public ref class CodeAttributeArgument
public class CodeAttributeArgument
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDispatch)]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class CodeAttributeArgument
type CodeAttributeArgument = class
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDispatch)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
[<System.Serializable>]
type CodeAttributeArgument = class
Public Class CodeAttributeArgument
Наследование
CodeAttributeArgument
Атрибуты

Примеры

Следующий код создает класс и добавляет атрибуты кода, чтобы объявить, что класс является сериализуемым и устаревшим.

#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");

    // Use attributes to mark the class as serializable and obsolete.
    CodeAttributeDeclaration^ codeAttrDecl =
        gcnew CodeAttributeDeclaration("System.Serializable");
    class1->CustomAttributes->Add(codeAttrDecl);

    CodeAttributeArgument^ codeAttr =
        gcnew CodeAttributeArgument( gcnew CodePrimitiveExpression("This class is obsolete."));
    codeAttrDecl = gcnew CodeAttributeDeclaration("System.Obsolete", codeAttr);
    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:
//
//[System.Serializable()]
//[System.Obsolete("This class is obsolete.")]
//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");

        // Use attributes to mark the class as serializable and obsolete.
        CodeAttributeDeclaration codeAttrDecl =
            new CodeAttributeDeclaration("System.Serializable");
        class1.CustomAttributes.Add(codeAttrDecl);

        CodeAttributeArgument codeAttr =
            new CodeAttributeArgument( new CodePrimitiveExpression("This class is obsolete."));
        codeAttrDecl = new CodeAttributeDeclaration("System.Obsolete", codeAttr);
        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:
//
// [System.Serializable()]
// [System.Obsolete("This class is obsolete.")]
// 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")

        ' Use attributes to mark the class as serializable and obsolete.
        Dim codeAttrDecl As New CodeAttributeDeclaration("System.Serializable")
        class1.CustomAttributes.Add(codeAttrDecl)

        Dim codeAttr As _
            New CodeAttributeArgument( new CodePrimitiveExpression("This class is obsolete."))
        codeAttrDecl = New CodeAttributeDeclaration("System.Obsolete", codeAttr)
        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:
'
' <System.Serializable(),  _
'  System.Obsolete("This class is obsolete.")>  _
' Public Class Class1
' End Class

Комментарии

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

Свойство Value указывает значение аргумента . Свойство Name при использовании указывает имя свойства атрибута, которому присваивается значение.

Объявления атрибутов часто инициализируются с помощью ряда аргументов, которые передаются в конструктор атрибута во время выполнения. Чтобы предоставить аргументы конструктору для атрибута, добавьте CodeAttributeArgument для каждого аргумента в коллекцию ArgumentsCodeAttributeDeclaration. Необходимо инициализировать Value только свойство каждого из них CodeAttributeArgument . Порядок аргументов в коллекции должен соответствовать порядку аргументов в сигнатуре метода конструктора для атрибута .

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

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

CodeAttributeArgument()

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

CodeAttributeArgument(CodeExpression)

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

CodeAttributeArgument(String, CodeExpression)

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

Свойства

Name

Возвращает или задает имя атрибута.

Value

Получает или задает значение для аргумента атрибута.

Методы

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

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

Служит хэш-функцией по умолчанию.

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

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

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

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

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

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

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

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

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