Заглавная страница Избранные статьи Случайная статья Познавательные статьи Новые добавления Обратная связь FAQ Написать работу КАТЕГОРИИ: АрхеологияБиология Генетика География Информатика История Логика Маркетинг Математика Менеджмент Механика Педагогика Религия Социология Технологии Физика Философия Финансы Химия Экология ТОП 10 на сайте Приготовление дезинфицирующих растворов различной концентрацииТехника нижней прямой подачи мяча. Франко-прусская война (причины и последствия) Организация работы процедурного кабинета Смысловое и механическое запоминание, их место и роль в усвоении знаний Коммуникативные барьеры и пути их преодоления Обработка изделий медицинского назначения многократного применения Образцы текста публицистического стиля Четыре типа изменения баланса Задачи с ответами для Всероссийской олимпиады по праву Мы поможем в написании ваших работ! ЗНАЕТЕ ЛИ ВЫ?
Влияние общества на человека
Приготовление дезинфицирующих растворов различной концентрации Практические работы по географии для 6 класса Организация работы процедурного кабинета Изменения в неживой природе осенью Уборка процедурного кабинета Сольфеджио. Все правила по сольфеджио Балочные системы. Определение реакций опор и моментов защемления |
Fixed size buffers in expressions↑ ⇐ ПредыдущаяСтр 26 из 26 Содержание книги
Поиск на нашем сайте
Member lookup (§7.3) of a fixed size buffer member proceeds exactly like member lookup of a field. A fixed size buffer can be referenced in an expression using a simple-name (§7.5.2) or a member-access (§7.5.4). When a fixed size buffer member is referenced as a simple name, the effect is the same as a member access of the form this.I, where I is the fixed size buffer member. In a member access of the form E.I, if E is of a struct type and a member lookup of I in that struct type identifies a fixed size member, then E.I is evaluated an classified as follows: · If the expression E.I does not occur in an unsafe context, a compile-time error occurs. · If E is classified as a value, a compile-time error occurs. · Otherwise, if E is a moveable variable (§18.3) and the expression E.I is not a fixed-pointer-initializer (§18.6), a compile-time error occurs. · Otherwise, E references a fixed variable and the result of the expression is a pointer to the first element of the fixed size buffer member I in E. The result is of type S*, where S is the element type of I, and is classified as a value. The subsequent elements of the fixed size buffer can be accessed using pointer operations from the first element. Unlike access to arrays, access to the elements of a fixed size buffer is an unsafe operation and is not range checked. The following example declares and uses a struct with a fixed size buffer member. unsafe struct Font class Test unsafe static void Main() Definite assignment checking Fixed size buffers are not subject to definite assignment checking (§5.3), and fixed size buffer members are ignored for purposes of definite assignment checking of struct type variables. When the outermost containing struct variable of a fixed size buffer member is a static variable, an instance variable of a class instance, or an array element, the elements of the fixed size buffer are automatically initialized to their default values (§5.2). In all other cases, the initial content of a fixed size buffer is undefined. Stack allocation In an unsafe context, a local variable declaration (§8.5.1) may include a stack allocation initializer which allocates memory from the call stack. local-variable-initializer: stackalloc-initializer: The unmanaged-type indicates the type of the items that will be stored in the newly allocated location, and the expression indicates the number of these items. Taken together, these specify the required allocation size. Since the size of a stack allocation cannot be negative, it is a compile-time error to specify the number of items as a constant-expression that evaluates to a negative value. A stack allocation initializer of the form stackalloc T[E] requires T to be an unmanaged type (§18.2) and E to be an expression of type int. The construct allocates E * sizeof(T) bytes from the call stack and returns a pointer, of type T*, to the newly allocated block. If E is a negative value, then the behavior is undefined. If E is zero, then no allocation is made, and the pointer returned is implementation-defined. If there is not enough memory available to allocate a block of the given size, a System.StackOverflowException is thrown. The content of the newly allocated memory is undefined. Stack allocation initializers are not permitted in catch or finally blocks (§8.10). There is no way to explicitly free memory allocated using stackalloc. All stack allocated memory blocks created during the execution of a function member are automatically discarded when that function member returns. This corresponds to the alloca function, an extension commonly found in C and C++ implementations. In the example using System; class Test static void Main() { a stackalloc initializer is used in the IntToString method to allocate a buffer of 16 characters on the stack. The buffer is automatically discarded when the method returns. Dynamic memory allocation Except for the stackalloc operator, C# provides no predefined constructs for managing non-garbage collected memory. Such services are typically provided by supporting class libraries or imported directly from the underlying operating system. For example, the Memory class below illustrates how the heap functions of an underlying operating system might be accessed from C#: using System; public unsafe class Memory static int ph = GetProcessHeap(); // Private instance constructor to prevent instantiation. private Memory() {} // Allocates a memory block of the given size. The allocated memory is public static void* Alloc(int size) { // Copies count bytes from src to dst. The source and destination public static void Copy(void* src, void* dst, int count) { // Frees a memory block. public static void Free(void* block) { // Re-allocates a memory block. If the reallocation request is for a public static void* ReAlloc(void* block, int size) { // Returns the size of a memory block. public static int SizeOf(void* block) { // Heap API flags const int HEAP_ZERO_MEMORY = 0x00000008; // Heap API functions [DllImport("kernel32")] [DllImport("kernel32")] [DllImport("kernel32")] [DllImport("kernel32")] [DllImport("kernel32")] An example that uses the Memory class is given below: class Test The example allocates 256 bytes of memory through Memory.Alloc and initializes the memory block with values increasing from 0 to 255. It then allocates a 256 element byte array and uses Memory.Copy to copy the contents of the memory block into the byte array. Finally, the memory block is freed using Memory.Free and the contents of the byte array are output on the console. A. Documentation comments C# provides a mechanism for programmers to document their code using a special comment syntax that contains XML text. In source code files, comments having a certain form can be used to direct a tool to produce XML from those commentsand the source code elements, which they precede. Comments using such syntax are called documentation comments. They must immediately precede a user-defined type (such as a class, delegate, or interface) or a member (such as a field, event, property, or method). The XML generation tool is called the documentation generator.(This generator could be, but need not be, the C# compiler itself.) The output produced by the documentation generator is called the documentation file.A documentation file is used as input to a documentation viewer;a tool intended to produce some sort of visual display of type information and its associated documentation. This specification suggests a set of tags to be used in documentation comments, but use of these tags is not required, and other tags may be used if desired, as long the rules of well-formed XML are followed. A.1 Introduction Comments having a special form can be used to direct a tool to produce XML from those commentsand the source code elements, which they precede. Such comments are single-line comments that start with three slashes (///), or delimited comments that start with a slash and two stars (/**). They must immediately precede a user-defined type (such as a class, delegate, or interface) or a member (such as a field, event, property, or method) that they annotate. Attribute sections (§17.2) are considered part of declarations, so documentation comments must precede attributes applied to a type or member. Syntax: single-line-doc-comment: delimited-doc-comment: In a single-line-doc-comment, if there is a whitespace character following the /// characters on each of the single-line-doc-comments adjacent to the current single-line-doc-comment, then that whitespace character is not included in the XML output. In a delimited-doc-comment, if the first non- whitespace character on the second line is an asterisk and the same pattern of optional whitespace characters and an asterisk character is repeated at the beginning of each of the line within the delimited-doc-comment, then the characters of the repeated pattern are not included in the XML output. The pattern may include whitespace characters after, as well as before, the asterisk character. Example: /// <summary>Class <c>Point</c> models a point in a two-dimensional The text within documentation comments must be well formed according to the rules of XML (http://www.w3.org/TR/REC-xml). If the XML is ill formed, a warning is generated and the documentation file will contain a comment saying that an error was encountered. Although developers are free to create their own set of tags, a recommended set is defined in §A.2. Some of the recommended tags have special meanings: · The <param> tag is used to describe parameters. If such a tag is used, the documentation generator must verify that the specified parameter exists and that all parameters are described in documentation comments. If such verification fails, the documentation generator issues a warning. · The crefattribute can be attached to any tag to provide a reference to a code element. The documentation generator must verify that this code element exists. If the verification fails, the documentation generator issues a warning. When looking for a name described in a cref attribute, the documentation generator must respect namespace visibility according to using statements appearing within the source code. For code elements that are generic, the normal generic syntax (ie “List<T>”) cannot be used because it produces invalid XML. Braces can be used instead of brackets (ie “List{T}”), or the XML escape syntax can be used (ie “List<T>”). · The <summary> tag is intended to be used by a documentation viewer to display additional information about a type or member. · The <include> tag includes information from an external XML file. Note carefully that the documentation file does not provide full information about the type and members (for example, it does not contain any type information). To get such information about a type or member, the documentation file must be used in conjunction with reflection on the actual type or member. A.2 Recommended tags The documentation generator must accept and process any tag that is valid according to the rules of XML. The following tags provide commonly used functionality in user documentation. (Of course, other tags are possible.)
A.2.1 <c> This tag provides a mechanism to indicate that a fragment of text within a description should be set in a special font such as that used for a block of code. For lines of actual code, use <code> (§A.2.2). Syntax: <c> text </c> Example: /// <summary>Class <c>Point</c> models a point in a two-dimensional public class Point A.2.2 <code> This tag is used to set one or more lines of source code or program output in some special font. For small code fragments in narrative, use <c> (§A.2.1). Syntax: <code> source code or program output </code> Example: /// <summary>This method changes the point's location by public void Translate(int xor, int yor) { A.2.3 <example> This tag allows example code within a comment, to specify how a method or other library member may be used. Ordinarily, this would also involve use of the tag <code> (§A.2.2) as well. Syntax: <example> description </example> Example: See <code> (§A.2.2) for an example. A.2.4 <exception> This tag provides a way to document the exceptions a method can throw. Syntax: <exception cref=" member "> description </exception> where cref=" member " The name of a member. The documentation generator checks that the given member exists and translates member to the canonical element name in the documentation file. description A description of the circumstances in which the exception is thrown. Example: public class DataBaseOperations A.2.5 <include> This tag allows including information from an XML document that is external to the source code file. The external file must be a well-formed XML document, and an XPath expression is applied to that document to specify what XML from that document to include. The <include> tag is then replaced with the selected XML from the external document. Syntax: <include file=" filename " path= " xpath " /> where file=" filename " The file name of an external XML file. The file name is interpreted relative to the file that contains the include tag. path= " xpath " An XPath expression that selects some of the XML in the external XML file. Example: If the source code contained a declaration like: /// <include file= " docs.xml " path= 'extradoc/class[@name="IntList"]/*' /> and the external file “ docs.xml ” had the following contents: <?xml version= "1.0"?> then the same documentation is output as if the source code contained: /// <summary> A.2.6 <list> This tag is used to create a list or table of items. It may contain a <listheader> block to define the heading row of either a table or definition list. (When defining a table, only an entry for term in the heading need be supplied.) Each item in the list is specified with an <item> block. When creating a definition list, both term and description must be specified. However, for a table, bulleted list, or numbered list, only description need be specified. Syntax: <list type="bullet" | "number" | "table"> where term The term to define, whose definition is in description. description Either an item in a bullet or numbered list, or the definition of a term. Example: public class MyClass A.2.7 <para> This tag is for use inside other tags, such as <summary> (§A.2.11) or <returns> (§A.2.12), and permits structure to be added to text. Syntax: <para> content </para> where content The text of the paragraph. Example: /// <summary>This is the entry point of the Point class testing program. A.2.8 <param> This tag is used to describe a parameter for a method, constructor, or indexer. Syntax: <param name=" name "> description </param> where name The name of the parameter. description A description of the parameter. Example: /// <summary>This method changes the point's location to A.2.9 <paramref> This tag is used to indicate that a word is a parameter. The documentation file can be processed to format this parameter in some distinct way. Syntax: <paramref name=" name "/> where name The name of the parameter. Example: /// <summary>This constructor initializes the new Point to public Point(int xor, int yor) { A.2.10 <permission> This tag allows the security accessibility of a member to be documented. Syntax: <permission cref=" member "> description </permission> where cref=" member " The name of a member. The documentation generator checks that the given code element exists and translates member to the canonical element name in the documentation file. description A description of the access to the member. Example: /// <permission cref="System.Security.PermissionSet">Everyone can public static void Test() { A.2.11 <remark> This tag is used to specify extra information about a type. (Use <summary> (§A.2.15) to describe the type itself and the members of a type.) Syntax: <remark> description </remark> where description The text of the remark. Example: /// <summary>Class <c>Point</c> models a point in a A.2.12 <returns> This tag is used to describe the return value of a method. Syntax: <returns> description </returns> where description A description of the return value. Example: /// <summary>Report a point's location as a string.</summary> A.2.13 <see> This tag allows a link to be specified within text. Use <seealso> (§A.2.14) to indicate text that is to appear in a See Also section. Syntax: <see cref=" member "/> where cref=" member " The name of a member. The documentation generator checks that the given code element exists and changes member to the element name in the generated documentation file. Example: /// <summary>This method changes the point's location to /// <summary>This method changes the point's location by A.2.14 <seealso> This tag allows an entry to be generated for the See Also section. Use <see> (§A.2.13) to specify a link from within text. Syntax: <seealso cref=" member "/> where cref=" member " The name of a member. The documentation generator checks that the given code element exists and changes member to the element name in the generated documentation file. Example: /// <summary>This method determines whether two Points have the same A.2.15 <summary> This tag can be used to describe a type or a member of a type. Use <remark> (§A.2.11) to describe the type itself. Syntax: <summary> description </summary> where description A summary of the type or member. Example: /// <summary>This constructor initializes the new Point to (0,0).</summary> A.2.16 <value> This tag allows a property to be described. Syntax: <value> property description </value> where property description A description for the property. Example: /// <value>Property <c>X</c> represents the point's x-coordinate.</value> A.2.17 <typeparam> This tag is used to describe a generic type parameter for a class, struct, interface, delegate, or method. Syntax: <typeparam name=" name "> description </typeparam> where name The name of the type parameter. description A description of the type parameter. Example: /// <summary>A generic list class.</summary> A.2.18 <typeparamref> This tag is used to indicate that a word is a type parameter. The documentation file can be processed to format this type parameter in some distinct way. Syntax: <typeparamref name=" name "/> where name The name of the type parameter. Example: /// <summary>This method fetches data and returns a list of <typeparamref name=”T”> ”/>”>.</summary> public List<T> FetchData<T>(string query) { A.3 Processing the documentation file The documentation generator generates an ID stringfor each element in the source code that is tagged with a documentation comment. This ID string uniquely identifies a source element. A documentation viewer can use an ID string to identify the corresponding metadata/reflection item to which the documentation applies. The documentation file is not a hierarchical representation of the source code; rather, it is a flat list with a generated ID string for each element. A.3.1 ID string format The documentation generator observes the following rules when it generates the ID strings: · No white space is placed in the string. · The first part of the string identifies the kind of member being documented, via a single character followed by a colon. The following kinds of members are defined:
· The second part of the string is the fully qualified name of the element, starting at the root of the namespace. The name of the element, its enclosing type(s), and namespace are separated by periods. If the name of the item itself has periods, they are replaced by # (U+0023) characters. (It is assumed that no element has this character in its name.) · For methods and properties with arguments, the argument list follows, enclosed in parentheses. For those without arguments, the parentheses are omitted. The arguments are separated by commas. The encoding of each argument is the same as a CLI signature, as follows: o Arguments are represented by their documentation name, which is based on their fully qualified name, modified as follows: Arguments that represent generic types have an appended “’” character followed by the number of type parameters Arguments having the out or ref modifier have an @ following their type name. Arguments passed by value or via params have no special notation. Arguments that are arrays are represented as [ lowerbound: size, …, lowerbound: size ] where the number of commas is the rank less one, and the lower bounds and size of each dimension, if known, are represented in decimal. If a lower bound or size is not specified, it is omitted. If the lower bound and size for a particular dimension are omitted, the “:” is omitted as well. Jagged arrays are represented by one “[]” per level. Arguments that have pointer types other than void are represented using a * following the type name. A void pointer is represented using a type name of System.Void. Arguments that refer to generic type parameters defined on types are encoded using the “`” character followed by the zero-based index of the type parameter. Arguments that use generic type parameters defined in methods use a double-backtick “``” instead of the “`” used for types. Arguments that refer to constructed generic types are encoded using the generic type, followed by “{“, followed by a comma-separated list of type arguments, followed by “}”. A.3.2 ID string examples The following examples each show a fragment of C# code, along with the ID string produced from each source element capable of having a documentation comment: · Types are represented using their fully qualified name, augmented with generic information: enum Color { Red, Blue, Green } namespace Acme struct ValueType {...} class Widget: IProcess public interface IMenuItem {...} public delegate void Del(int i); public enum Direction { North, South, East, West } class MyList<T> "T:Color" · Fields are represented by their fully qualified name: namespace Acme class Widget: IProcess private string message; "F:Acme.ValueType.total" · Constructors. namespace Acme public Widget() {...} public Widget(string s) {...} "M:Acme.Widget.#cctor" · Destructors. namespace Acme "M:Acme.Widget.Finalize" · Methods. namespace Acme class Widget: IProcess public static void M0() {...} class MyList<T> class UseList "M:Acme.ValueType.M(System.Int32)" · Properties and indexers. namespace Acme "P:Acme.Widget.Width" · Events. namespace Acme "E:Acme.Widget.AnEvent" · Unary operators. namespace Acme "M:Acme.Widget.op_UnaryPlus(Acme.Widget)" The complete set of unary operator function names used is as follows: op_UnaryPlus, op_UnaryNegation, op_LogicalNot, op_OnesComplement, op_Increment, op_Decrement, op_True, and op_False. · Binary operators. namespace Acme "M:Acme.Widget.op_Addition(Acme.Widget,Acme.Widget)" The complete set of binary operator function names used is as follows: op_Addition, op_Subtraction, op_Multiply, op_Division, op_Modulus, op_BitwiseAnd, op_BitwiseOr, op_ExclusiveOr, op_LeftShift, op_RightShift, op_Equality, op_Inequality, op_LessThan, op_LessThanOrEqual, op_GreaterThan, and op_GreaterThanOrEqual. · Conversion operators have a trailing “~” followed by the return type. namespace Acme "M:Acme.Widget.op_Explicit(Acme.Widget)~System.Int32" A.4 An example A.4.1 C# source code The following example shows the source code of a Point class: namespace Graphics /// <summary>Class <c>Point</c> models a point in a two-dimensional plane. /// <summary>Instance variable <c>x</c> represents the point's /// <summary>Instance variable <c>y</c> represents the point's /// <value>Property <c>X</c> represents the point's x-coordinate.</value> /// <value>Property <c>Y</c> represents the point's y-coordinate.</value> /// <summary>This constructor initializes the new Point to /// <summary>This constructor initializes the new Point to /// <summary>This method changes the point's location to /// <summary>This method changes the point's location by /// <summary>This method determines whether two Points have the same if (this == o) { if (GetType() == o.GetType()) { /// <summary>Report a point's location as a string.</summary> /// <summary>This operator determines whether two Points have the same if (p1.GetType() == p2.GetType()) { return false; /// <summary>This operator determines whether two Points have the same /// <summary>This is the entry point of the Point class testing A.4.2 Resulting XML Here is the output produced by one documentation generator when given the source code for class Point, shown above: <?xml version="1.0"?> <member name="F:Graphics.Point.x"> <member name="F:Graphics.Point.y"> <member name="M:Graphics.Point.#ctor"> <member name="M:Graphics.Point.#ctor(System.Int32,System.Int32)"> <member name="M:Graphics.Point.Move(System.Int32,System.Int32)"> <member <member name="M:Graphics.Point.Equals(System.Object)"> <member name="M:Graphics.Point.ToString"> <member <member <member name="M:Graphics.Point.Main"> <member name="P:Graphics.Point.X"> <member name="P:Graphics.Point.Y">
B. Grammar This appendix contains summaries of the lexical and syntactic grammars found in the main document, and of the grammar extensions for unsafe code. Grammar productions appear here in the same order that they appear in the main document. B.1 Lexical grammar input: input-section: input-section-part: input-elements: input-element: B.1.1 Line terminators new-line: B.1.2 Comments comment: single-line-comment: input-characters: input-character: new-line-character: delimited-comment: delimited-comment-text: delimited-comment-section: asterisks: not-slash-or-asterisk: B.1.3 White space whitespace: B.1.4 Tokens token: B.1.5 Unicode character escape sequences unicode-escape-sequence: B.1.6 Identifiers identifier: available-identifier: identifier-or-keyword: identifier-start-character: identifier-part-characters: identifier-part-character: letter-character: combining-character: decimal-digit-character: connecting-character: formatting-character: B.1.7 Keywords keyword: one of B.1.8 Literals literal: boolean-literal: integer-literal: decimal-integer-literal: decimal-digits: decimal-digit: one of integer-type-suffix: one of hexadecimal-integer-literal: hex-digits: hex-digit: one of real-literal: exponent-part: sign: one of real-type-suffix: one of character-literal: character: single-character: simple-escape-sequence: one of hexadecimal-escape-sequence: string-literal: regular-string-literal: regular-string-literal-characters: regular-string-literal-character: single-regular-string-literal-character: verbatim-string-literal: verbatim-string-literal-characters: verbatim-string-literal-character: single-verbatim-string-literal-character: quote-escape-sequence: null-literal: B.1.9 Operators and punctuators operator-or-punctuator: one of right-shift: right-shift-assignment: B.1.10 Pre-processing directives pp-directive: conditional-symbol: pp-expression: pp-or-expression: pp-and-expression: pp-equality-expression: pp-unary-expression: pp-primary-expression: pp-declaration: pp-new-line: pp-conditional: pp-if-section: pp-elif-sections: pp-elif-section: pp-else-section: pp-endif: conditional-section: skipped-section: skipped-section-part: skipped-characters: not-number-sign: pp-diagnostic: pp-message: pp-region: pp-start-region: pp-end-region: pp-line: line-indicator: file-name: file-name-characters: file-name-character: pp-pragma: pragma-body: pragma-warning-body:
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Последнее изменение этой страницы: 2016-12-14; просмотров: 409; Нарушение авторского права страницы; Мы поможем в написании вашей работы! infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 52.15.190.187 (0.014 с.) |