Поделиться через


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;
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 для каждого аргумента Arguments в коллекцию атрибута CodeAttributeDeclaration. 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)

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

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