CodeConstructor Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Представляет объявление для конструктора экземпляра типа.
public ref class CodeConstructor : System::CodeDom::CodeMemberMethod
public class CodeConstructor : System.CodeDom.CodeMemberMethod
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDispatch)]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class CodeConstructor : System.CodeDom.CodeMemberMethod
type CodeConstructor = class
inherit CodeMemberMethod
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDispatch)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
[<System.Serializable>]
type CodeConstructor = class
inherit CodeMemberMethod
Public Class CodeConstructor
Inherits CodeMemberMethod
- Наследование
- Атрибуты
Примеры
В этом примере показано, как CodeConstructor объявить несколько типов конструкторов.
// This example declares two types, one of which inherits from another,
// and creates a set of different styles of constructors using CodeConstructor.
// Creates a new CodeCompileUnit to contain the program graph.
CodeCompileUnit CompileUnit = new CodeCompileUnit();
// Declares a new namespace object and names it.
CodeNamespace Samples = new CodeNamespace("Samples");
// Adds the namespace object to the compile unit.
CompileUnit.Namespaces.Add( Samples );
// Adds a new namespace import for the System namespace.
Samples.Imports.Add( new CodeNamespaceImport("System") );
// Declares a new type and names it.
CodeTypeDeclaration BaseType = new CodeTypeDeclaration("BaseType");
// Adds the new type to the namespace object's type collection.
Samples.Types.Add(BaseType);
// Declares a default constructor that takes no arguments.
CodeConstructor defaultConstructor = new CodeConstructor();
defaultConstructor.Attributes = MemberAttributes.Public;
// Adds the constructor to the Members collection of the BaseType.
BaseType.Members.Add(defaultConstructor);
// Declares a constructor that takes a string argument.
CodeConstructor stringConstructor = new CodeConstructor();
stringConstructor.Attributes = MemberAttributes.Public;
// Declares a parameter of type string named "TestStringParameter".
stringConstructor.Parameters.Add( new CodeParameterDeclarationExpression("System.String", "TestStringParameter") );
// Adds the constructor to the Members collection of the BaseType.
BaseType.Members.Add(stringConstructor);
// Declares a type that derives from BaseType and names it.
CodeTypeDeclaration DerivedType = new CodeTypeDeclaration("DerivedType");
// The DerivedType class inherits from the BaseType class.
DerivedType.BaseTypes.Add( new CodeTypeReference("BaseType") );
// Adds the new type to the namespace object's type collection.
Samples.Types.Add(DerivedType);
// Declare a constructor that takes a string argument and calls the base class constructor with it.
CodeConstructor baseStringConstructor = new CodeConstructor();
baseStringConstructor.Attributes = MemberAttributes.Public;
// Declares a parameter of type string named "TestStringParameter".
baseStringConstructor.Parameters.Add( new CodeParameterDeclarationExpression("System.String", "TestStringParameter") );
// Calls a base class constructor with the TestStringParameter parameter.
baseStringConstructor.BaseConstructorArgs.Add( new CodeVariableReferenceExpression("TestStringParameter") );
// Adds the constructor to the Members collection of the DerivedType.
DerivedType.Members.Add(baseStringConstructor);
// Declares a constructor overload that calls another constructor for the type with a predefined argument.
CodeConstructor overloadConstructor = new CodeConstructor();
overloadConstructor.Attributes = MemberAttributes.Public;
// Sets the argument to pass to a base constructor method.
overloadConstructor.ChainedConstructorArgs.Add( new CodePrimitiveExpression("Test") );
// Adds the constructor to the Members collection of the DerivedType.
DerivedType.Members.Add(overloadConstructor);
// Declares a constructor overload that calls the default constructor for the type.
CodeConstructor overloadConstructor2 = new CodeConstructor();
overloadConstructor2.Attributes = MemberAttributes.Public;
overloadConstructor2.Parameters.Add( new CodeParameterDeclarationExpression("System.Int32", "TestIntParameter") );
// Sets the argument to pass to a base constructor method.
overloadConstructor2.ChainedConstructorArgs.Add( new CodeSnippetExpression("") );
// Adds the constructor to the Members collection of the DerivedType.
DerivedType.Members.Add(overloadConstructor2);
// A C# code generator produces the following source code for the preceeding example code:
// public class BaseType {
//
// public BaseType() {
// }
//
// public BaseType(string TestStringParameter) {
// }
// }
//
// public class DerivedType : BaseType {
//
// public DerivedType(string TestStringParameter) :
// base(TestStringParameter) {
// }
//
// public DerivedType() :
// this("Test") {
// }
//
// public DerivedType(int TestIntParameter) :
// this() {
// }
// }
' This example declares two types, one of which inherits from another,
' and creates a set of different styles of constructors using CodeConstructor.
' Creates a new CodeCompileUnit to contain the program graph.
Dim CompileUnit As New CodeCompileUnit()
' Declares a new namespace object and names it.
Dim Samples As New CodeNamespace("Samples")
' Adds the namespace object to the compile unit.
CompileUnit.Namespaces.Add(Samples)
' Adds a new namespace import for the System namespace.
Samples.Imports.Add(New CodeNamespaceImport("System"))
' Declares a new type and names it.
Dim BaseType As New CodeTypeDeclaration("BaseType")
' Adds the new type to the namespace object's type collection.
Samples.Types.Add(BaseType)
' Declares a default constructor that takes no arguments.
Dim defaultConstructor As New CodeConstructor()
defaultConstructor.Attributes = MemberAttributes.Public
' Adds the constructor to the Members collection of the BaseType.
BaseType.Members.Add(defaultConstructor)
' Declares a constructor that takes a string argument.
Dim stringConstructor As New CodeConstructor()
stringConstructor.Attributes = MemberAttributes.Public
' Declares a parameter of type string named "TestStringParameter".
stringConstructor.Parameters.Add(New CodeParameterDeclarationExpression("System.String", "TestStringParameter"))
' Adds the constructor to the Members collection of the BaseType.
BaseType.Members.Add(stringConstructor)
' Declares a type that derives from BaseType and names it.
Dim DerivedType As New CodeTypeDeclaration("DerivedType")
' The DerivedType class inherits from the BaseType class.
DerivedType.BaseTypes.Add(New CodeTypeReference("BaseType"))
' Adds the new type to the namespace object's type collection.
Samples.Types.Add(DerivedType)
' Declare a constructor that takes a string argument and calls the base class constructor with it.
Dim baseStringConstructor As New CodeConstructor()
baseStringConstructor.Attributes = MemberAttributes.Public
' Declares a parameter of type string named "TestStringParameter".
baseStringConstructor.Parameters.Add(New CodeParameterDeclarationExpression("System.String", "TestStringParameter"))
' Calls a base class constructor with the TestStringParameter parameter.
baseStringConstructor.BaseConstructorArgs.Add(New CodeVariableReferenceExpression("TestStringParameter"))
' Adds the constructor to the Members collection of the DerivedType.
DerivedType.Members.Add(baseStringConstructor)
' Declares a constructor overload that calls another constructor for the type with a predefined argument.
Dim overloadConstructor As New CodeConstructor()
overloadConstructor.Attributes = MemberAttributes.Public
' Sets the argument to pass to a base constructor method.
overloadConstructor.ChainedConstructorArgs.Add(New CodePrimitiveExpression("Test"))
' Adds the constructor to the Members collection of the DerivedType.
DerivedType.Members.Add(overloadConstructor)
' Declares a constructor overload that calls another constructor for the type.
Dim overloadConstructor2 As New CodeConstructor()
overloadConstructor2.Attributes = MemberAttributes.Public
overloadConstructor2.Parameters.Add( New CodeParameterDeclarationExpression("System.Int32", "TestIntParameter") )
' Sets the argument to pass to a base constructor method.
overloadConstructor2.ChainedConstructorArgs.Add(New CodeSnippetExpression(""))
' Adds the constructor to the Members collection of the DerivedType.
DerivedType.Members.Add(overloadConstructor2)
' A Visual Basic code generator produces the following source code for the preceeding example code:
' Public Class BaseType
'
' Public Sub New()
' MyBase.New
' End Sub
'
' Public Sub New(ByVal TestStringParameter As String)
' MyBase.New
' End Sub
' End Class
'
' Public Class DerivedType
' Inherits BaseType
'
' Public Sub New(ByVal TestStringParameter As String)
' MyBase.New(TestStringParameter)
' End Sub
'
' Public Sub New()
' Me.New("Test")
' End Sub
'
' Public Sub New(ByVal TestIntParameter As Integer)
' Me.New()
' End Sub
' End Class
Комментарии
CodeConstructor можно использовать для представления объявления конструктора экземпляра для типа. Используется CodeTypeConstructor для объявления статического конструктора для типа.
Если конструктор вызывает конструктор базового класса, задайте аргументы конструктора для конструктора базового класса в свойстве BaseConstructorArgs . Если конструктор перегружает другой конструктор для типа, задайте аргументы конструктора для передачи в перегруженный конструктор типов в свойстве ChainedConstructorArgs .
Конструкторы
| Имя | Описание |
|---|---|
| CodeConstructor() |
Инициализирует новый экземпляр класса CodeConstructor. |
Свойства
| Имя | Описание |
|---|---|
| Attributes |
Возвращает или задает атрибуты элемента. (Унаследовано от CodeTypeMember) |
| BaseConstructorArgs |
Возвращает коллекцию аргументов базового конструктора. |
| ChainedConstructorArgs |
Возвращает коллекцию аргументов конструктора в цепочке. |
| Comments |
Возвращает коллекцию комментариев для элемента типа. (Унаследовано от CodeTypeMember) |
| CustomAttributes |
Возвращает или задает настраиваемые атрибуты элемента. (Унаследовано от CodeTypeMember) |
| EndDirectives |
Возвращает конечные директивы для элемента. (Унаследовано от CodeTypeMember) |
| ImplementationTypes |
Возвращает типы данных интерфейсов, реализованных этим методом, если не является частной реализацией метода, которая указывается свойством PrivateImplementationType . (Унаследовано от CodeMemberMethod) |
| LinePragma |
Возвращает или задает строку, в которой происходит оператор-член типа. (Унаследовано от CodeTypeMember) |
| Name |
Возвращает или задает имя члена. (Унаследовано от CodeTypeMember) |
| Parameters |
Возвращает объявления параметров для метода. (Унаследовано от CodeMemberMethod) |
| PrivateImplementationType |
Возвращает или задает тип данных интерфейса, который этот метод, если закрытый, реализует метод, если таковой имеется. (Унаследовано от CodeMemberMethod) |
| ReturnType |
Возвращает или задает тип данных возвращаемого значения метода. (Унаследовано от CodeMemberMethod) |
| ReturnTypeCustomAttributes |
Возвращает настраиваемые атрибуты возвращаемого типа метода. (Унаследовано от CodeMemberMethod) |
| StartDirectives |
Возвращает директивы start для члена. (Унаследовано от CodeTypeMember) |
| Statements |
Возвращает инструкции в методе. (Унаследовано от CodeMemberMethod) |
| TypeParameters |
Возвращает параметры типа для текущего универсального метода. (Унаследовано от CodeMemberMethod) |
| UserData |
Возвращает определяемые пользователем данные для текущего объекта. (Унаследовано от CodeObject) |
Методы
| Имя | Описание |
|---|---|
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |
События
| Имя | Описание |
|---|---|
| PopulateImplementationTypes |
Событие, которое будет возникать при ImplementationTypes первом доступе к коллекции. (Унаследовано от CodeMemberMethod) |
| PopulateParameters |
Событие, которое будет возникать при Parameters первом доступе к коллекции. (Унаследовано от CodeMemberMethod) |
| PopulateStatements |
Событие, которое будет возникать при Statements первом доступе к коллекции. (Унаследовано от CodeMemberMethod) |