Assemblies and the Global Assembly Cache 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

Assemblies and the Global Assembly Cache



An assembly is a fundamental building block of any.NET Framework application. For example, when you build a simple C# application, Visual Studio creates an assembly in the form of a single portable executable (PE) file, specifically an EXE or DLL.

Assemblies contain metadata that describe their own internal version number and details of all the data and object types they contain. For more information see Assembly Manifest.

Assemblies are only loaded as they are required. If they are not used, they are not loaded. This means that assemblies can be an efficient way to manage resources in larger projects.

Assemblies can contain one or more modules. For example, larger projects may be planned in such a way that several individual developers work on separate modules, all coming together to create a single assembly.

Assemblies Overview

Assemblies have the following properties:

· Assemblies are implemented as.exe or.dll files.

· You can share an assembly between applications by putting it in the Global Assembly Cache.

· Assemblies must be strong-named before they can be included in the Global Assembly Cache. For more information, see Strong-Named Assemblies.

· Assemblies are only loaded into memory if they are required.

· You can programmatically obtain information about an assembly by using reflection. For more information, see the topic Reflection.

· If you want to load an assembly only to inspect it, use a method such as ReflectionOnlyLoadFrom.

· You can use two versions of the same assembly in a single application.

 


Сборки и глобальный кэш сборок

Сборка является основным строительным блоком любого приложения.NET Framework. Например, при создании простого приложения C# в Visual Studio создается сборка в виде одиночного переносимого исполняемого файла (PE) с расширением EXE или DLL.

Сборки содержат метаданные, описывающие их внутренний номер версии и сведения о содержащихся в сборке данных и типах объектов. Дополнительные сведения см. в разделе Манифест сборки.

Сборки загружаются только по мере необходимости. Если сборки не используются, они не загружаются. Благодаря этому сборки обеспечивают эффективное управление ресурсами в крупных проектах.

Сборки могут содержать один или несколько модулей. Например, крупные проекты могут быть спланированы таким образом, чтобы несколько разработчиков работали каждый над своим модулем, а вместе эти модули образовывали одну сборку. Дополнительные сведения о модулях см. в разделе Практическое руководство. Создание многофайловой сборки.

Общие сведения о сборках

Сборки имеют следующие свойства.

· Сборки реализованы как EXE- или DLL-файлы.

· Сборки можно поместить в глобальный кэш сборок, чтобы обеспечить их использование несколькими приложениями.

· В глобальный кэш сборок могут быть включены только сборки со строгими именами. Дополнительные сведения см. в разделе Сборки со строгими именами.

· Сборки загружаются в память только по мере необходимости.

· Для программного получения сведений о сборок используется класс reflection. Дополнительные сведения см. в разделе класс Reflection.

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

· Можно необходимо использовать две версии одной и той же сборки в одном приложении. Дополнительные сведения см. в разделе псевдоним extern.

 


Attributes

Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth). After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection.

Attributes occur in two forms:

· Attributes that are defined in the common language runtime (CLR).

· Custom attributes that you can create, to add extra information to your code. This information can later be retrieved programmatically.

In this example, the TypeAttributes..::.Serializable attribute is used to apply a specific characteristic to a class:

[System.Serializable] public class SampleClass { // Objects of this type can be serialized. }

Attribute Overview

Attributes have the following properties:

· Attributes add metadata to your program. Metadata is information embedded in your program such as compiler instructions or descriptions of data.

· Your program can examine its own metadata by using reflection.

· Attributes are generally used when you interact with COM.

 


Атрибуты

Атрибуты предоставляют эффективный метод связывания декларативной информации с кодом C# (типы, методы, свойства и т. д.). Атрибут, связанный с сущностью программы, может быть запрошен во время выполнения с помощью метода, называемого отражением.. Дополнительные сведения см. в разделе Отражение.

Существует две формы атрибутов.

· Атрибуты, которые определены в среде CLR.

· Пользовательские атрибуты, которые можно создать, чтобы добавить в код дополнительные сведения. Затем эти сведения можно извлечь программным путем.

В этом примере для применения определенных характеристик к классу используется атрибут TypeAttributes..::.Serializable.

[System.Serializable] public class SampleClass { // Objects of this type can be serialized. }

Общие сведения об атрибутах

Атрибуты имеют следующие параметры.

· Атрибуты добавляют в программу метаданные. Метаданные — это сведения, встроенные в программу, например инструкции компилятора или описания данных.

· Программа может проверить собственные метаданные с помощью отражения.

· Атрибуты обычно используются при взаимодействии с COM.

 


Using Attributes

Attributes can be placed on most any declaration, though a specific attribute might restrict the types of declarations on which it is valid. Syntactically, an attribute is specified by placing the name of the attribute, enclosed in square brackets, in front of the declaration of the entity to which it applies. For example, a method with the attribute DllImport is declared like this:

[System.Runtime.InteropServices.DllImport("user32.dll")] extern static void SampleMethod();

Many attributes have parameters, which can be either positional, unnamed, or named. Any positional parameters must be specified in a certain order and cannot be omitted; named parameters are optional and can be specified in any order. Positional parameters are specified first. For example, these three attributes are equivalent:

[DllImport("user32.dll")] [DllImport("user32.dll", SetLastError=false, ExactSpelling=false)] [DllImport("user32.dll", ExactSpelling=false, SetLastError=false)]

The first parameter, the DLL name, is positional and always comes first; the others are named. In this case, both named parameters default to false, so they can be omitted. Refer to the individual attribute's documentation for information on default parameter values.

More than one attribute can be placed on a declaration, either separately or within the same set of brackets:

void MethodA([In][Out] ref double x) { } void MethodB([Out][In] ref double x) { } void MethodC([In, Out] ref double x) { }

Some attributes can be specified more than once for a given entity. An example of such a multiuse attribute is Conditional:

[Conditional("DEBUG"), Conditional("TEST1")] void TraceMethod() { //... }
Note:
By convention, all attribute names end with the word "Attribute" to distinguish them from other items in the.NET Framework. However, you do not need to specify the attribute suffix when using attributes in code. For example, [DllImport] is equivalent to [DllImportAttribute], but DllImportAttribute is the attribute's actual name in the.NET Framework.

Использование атрибутов

Атрибуты могут быть размещены в большинстве объявлений, хотя определенный атрибут может ограничить типы объявлений, в которых он допустим. Синтаксически атрибут указывается путем размещения его имени, заключенного в квадратные скобки, в начале объявления сущности, к которой он применяется. Например, объявление метода с атрибутом DllImport выглядит следующим образом.

ß---

Многие атрибуты имеют параметры, которые могут быть либо позиционными, неименованными, либо именованными. Именованные параметры следует указывать в определенном порядке, их нельзя опустить; именованные параметры являются необязательными и могут быть указаны в любой последовательности. Сначала указываются позиционные параметры. Например, следующие три атрибута являются эквивалентными.

ß----

Первый параметр — имя библиотеки DLL — является позиционным и всегда стоит на первом месте; остальные являются именованными. В этом случае оба именованных параметра по умолчанию имеют значение "false" и могут быть пропущены. Сведения о заданных по умолчанию значениях параметров см. в документации по отдельному атрибуту.

В объявлении можно разместить несколько атрибутов — либо по отдельности, либо в одном наборе скобок.

ß-------

Для заданной сущности некоторые атрибуты можно указать несколько раз. Примером такого многократно используемого атрибута является Conditional.

ß----

Примечание.
Чтобы отличать атрибуты от других элементов платформы.NET Framework, используется соглашение, по которому все имена атрибутов заканчиваются словом "Attribute" ("атрибут"). Однако нет необходимости указывать суффикс атрибута при его использовании в коде. Например, [DllImport] эквивалентен [DllImportAttribute], однако DllImportAttribute является фактическим именем атрибута в платформе.NET Framework.

 


How to: Create a C/C++ Union Using Attributes

By using attributes you can customize how structs are laid out in memory. For example, you can create what is known as a union in C/C++ by using the StructLayout(LayoutKind.Explicit) and FieldOffset attributes.

Example

In this code segment, all of the fields of TestUnion start at the same location in memory.

[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)] struct TestUnion { [System.Runtime.InteropServices.FieldOffset(0)] public int i; [System.Runtime.InteropServices.FieldOffset(0)] public double d; [System.Runtime.InteropServices.FieldOffset(0)] public char c; [System.Runtime.InteropServices.FieldOffset(0)] public byte b; }

The following is another example where fields start at different explicitly set locations.

[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)] struct TestExplicit { [System.Runtime.InteropServices.FieldOffset(0)] public long lg;   [System.Runtime.InteropServices.FieldOffset(0)] public int i1;   [System.Runtime.InteropServices.FieldOffset(4)] public int i2;   [System.Runtime.InteropServices.FieldOffset(8)] public double d;   [System.Runtime.InteropServices.FieldOffset(12)] public char c;   [System.Runtime.InteropServices.FieldOffset(14)] public byte b; }

The two int fields, i1 and i2, share the same memory locations as lg. This sort of control over struct layout is useful when using platform invocation.


Создание объединения C/C++ с помощью атрибутов

Использование атрибутов позволяет настраивать расположение структур в памяти. Например, можно создать так называемое объединение в языках C/C++ с помощью атрибутов StructLayout(LayoutKind.Explicit) и FieldOffset.

Пример

В этом сегменте кода все поля объединения TestUnion начинаются с одного адреса в памяти.

ß-----

 

 

Ниже приведен еще один пример, в котором поля начинаются с разных явно заданных адресов.

ß-----

 

 

Два поля int, i1 и i2, совместно используют те же адреса в памяти, что и lg. Такое управление расположением структуры полезно при использовании вызова неуправляемого кода.

 


Common Attributes

This section describes the attributes that are most commonly used in C# programs.

Conditional

Makes the execution of a method dependent on a preprocessing identifier. The Conditional attribute is an alias for ConditionalAttribute, and can be applied to a method or an attribute class.

In this example, Conditional is applied to a method to enable or disable the display of program-specific diagnostic information:

#define TRACE_ON using System; using System.Diagnostics;   public class Trace { [Conditional("TRACE_ON")] public static void Msg(string msg) { Console.WriteLine(msg); } }   public class ProgramClass { static void Main() { Trace.Msg("Now in Main..."); Console.WriteLine("Done."); } }

If the TRACE_ON identifier is not defined, no trace output will be displayed.

The Conditional attribute is often used with the DEBUG identifier to enable trace and logging features for debug builds but not in release builds, like this:

[Conditional("DEBUG")] static void DebugMethod() { }

 


Общие атрибуты

В этом разделе описаны атрибуты, наиболее часто используемые в программах на языке C#.

Conditional

Делает выполнение метода зависимым от идентификатора предварительной обработки. Атрибут Conditional является псевдонимом для ConditionalAttribute и может применяться к методу или атрибуту class.

В данном примере атрибут Conditional применяется к методу для включения и отключения отображения диагностической информации для конкретной программы:

ß----

 

 

Если идентификатор TRACE_ON не задан, выходные данные трассировки не отображаются.

Атрибут Conditional часто используется с идентификатором DEBUG для разрешения функций трассировки и ведения журнала в построениях отладки, но не в построениях выпуска:

[Conditional("DEBUG")] static void DebugMethod() { }

 


Remarks

When a method marked as conditional is called, the presence or absence of the specified preprocessing symbol determines whether the call is included or omitted. If the symbol is defined, the call is included; otherwise, the call is omitted. Using Conditional is a cleaner, more elegant, and less error-prone alternative to enclosing methods inside #if and #endif, like this:

#if DEBUG void ConditionalMethod() { } #endif

A conditional method must be a method in a class or struct declaration and must have a return type of void.

Using multiple identifiers

If a method has multiple Conditional attributes, a call to the method is included if at least one of the conditional symbols is defined (in other words, the symbols are logically ORed together). In this example, the presence of either A or B will result in a method call:

[Conditional("A"), Conditional("B")] static void DoIfAorB() { //... }

To achieve the effect of logically ANDing symbols, you can define serial conditional methods. For example, the second method below will execute only if both A and B are defined:

[Conditional("A")] static void DoIfA() { DoIfAandB(); }   [Conditional("B")] static void DoIfAandB() { // Code to execute when both A and B are defined... }

Заметки

Если вызывается метод, помеченный как условный, то наличие или отсутствие заданного символа предварительной обработки определяет, включен этот вызов или опущен. Если символ указан, то вызов включается; в противном случае вызов опускается. Использование атрибута Conditional представляет собой более понятную, элегантную и менее подверженную ошибкам альтернативу вложению методов в #if и #endif:

#if DEBUG void ConditionalMethod() { } #endif

Условный метод должен быть методом в объявлении класса или структуры и должен возвращать тип void.



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 95; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.141.47.221 (0.041 с.)