Anda di halaman 1dari 8

Assembly:

Assemblies are the building blocks of .NET Framework applications; they form the fundamental
unit of deployment, version control, reuse, activation scoping, and security permissions. An
assembly is a collection of types and resources that are built to work together and form a logical
unit of functionality. An assembly provides the common language runtime with the information it
needs to be aware of type implementations.

In general, a static assembly can consist of four elements:


The assembly manifest, which contains assembly metadata.
Type metadata.
Microsoft intermediate language (MSIL) code that implements the types.
A set of resources.
Only the assembly manifest is required, but either types or resources are needed to give the
assembly any meaningful functionality.
There are several ways to group these elements in an assembly. You can group all elements in a
single physical file, which is shown in the following illustration.
Single-file assembly

Alternatively, the elements of an assembly can be contained in several files. These files can be
modules of compiled code (.netmodule), resources (such as .bmp or .jpg files), or other files
required by the application. Create a multifile assembly when you want to combine modules
written in different languages and to optimize downloading an application by putting seldom used
types in a module that is downloaded only when needed.
In the following illustration, the developer of a hypothetical application has chosen to separate
some utility code into a different module and to keep a large resource file (in this case a .bmp
image) in its original file. The .NET Framework downloads a file only when it is referenced;
keeping infrequently referenced code in a separate file from the application optimizes code
download.
Multifile assembly

Note The files that make up a multifile assembly are not physically linked by the file system.
Rather, they are linked through the assembly manifest and the common language runtime
manages them as a unit.
In this illustration, all three files belong to an assembly, as described in the assembly manifest
contained in MyAssembly.dll. To the file system, they are three separate files. Note that the file
Util.netmodule was compiled as a module because it contains no assembly information. When
the assembly was created, the assembly manifest was added to MyAssembly.dll, indicating its
relationship with Util.netmodule and Graphic.bmp.

Assembly Manifest
Every assembly, whether static or dynamic, contains a collection of data that describes how the
elements in the assembly relate to each other. The assembly manifest contains this assembly
metadata. An assembly manifest contains all the metadata needed to specify the assembly's
version requirements and security identity, and all metadata needed to define the scope of the
assembly and resolve references to resources and classes. The assembly manifest can be stored
in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a
standalone PE file that contains only assembly manifest information.
The following illustration shows the different ways the manifest can be stored.
Types of assemblies

For an assembly with one associated file, the manifest is incorporated into the PE file to form a
single-file assembly. You can create a multifile assembly with a standalone manifest file or with
the manifest incorporated into one of the PE files in the assembly.
Each assembly's manifest performs the following functions:
Enumerates the files that make up the assembly.
Governs how references to the assembly's types and resources map to the files that contain their
declarations and implementations.
Enumerates other assemblies on which the assembly depends.
Provides a level of indirection between consumers of the assembly and the assembly's
implementation details.
Renders the assembly self-describing.
Assembly Manifest Contents
The following table shows the information contained in the assembly manifest. The first four items
— the assembly name, version number, culture, and strong name information — make up the
assembly's identity.
Information Description

Assembly name A text string specifying the assembly's name.


Version number A major and minor version number, and a revision and
build number. The common language runtime uses
these numbers to enforce version policy.
Culture Information on the culture or language the assembly
supports. This information should be used only to
designate an assembly as a satellite assembly
containing culture- or language-specific information.
(An assembly with culture information is automatically
assumed to be a satellite assembly.)
Strong name information The public key from the publisher if the assembly has
been given a strong name.
List of all files in the A hash of each file contained in the assembly and a file
assembly name. Note that all files that make up the assembly
must be in the same directory as the file containing the
assembly manifest.
Type reference information Information used by the runtime to map a type
reference to the file that contains its declaration and
implementation. This is used for types that are
exported from the assembly.
Information on referenced A list of other assemblies that are statically referenced
assemblies by the assembly. Each reference includes the
dependent assembly's name, assembly metadata
(version, culture, operating system, and so on), and
public key, if the assembly is strong named.

Constructors

Constructors are class methods that are executed when an object of a given type is created.
Constructors have the same name as the class, and usually initialize the data members of the
new object.
A constructor that takes no parameters is called a default constructor. Default constructors are
invoked whenever an object is instantiated by using the new operator and no arguments are
provided to new.
Unless the class is static, classes without constructors are given a public default constructor by
the C# compiler in order to enable class instantiation

A private constructor is a special instance constructor. It is generally used in classes that contain
static members only. If a class has one or more private constructors and no public constructors,
other classes (except nested classes) cannot create instances of this class

A static constructor is used to initialize any static data, or to perform a particular action that needs
performed once only. It is called automatically before the first instance is created or any static
members are referenced.

Static constructors have the following properties:


A static constructor does not take access modifiers or have parameters.
A static constructor is called automatically to initialize the class before the first instance is created
or any static members are referenced.
A static constructor cannot be called directly.
The user has no control on when the static constructor is executed in the program.
A typical use of static constructors is when the class is using a log file and the constructor is used
to write entries to this file.
Static constructors are also useful when creating wrapper classes for unmanaged code, when the
constructor can call the LoadLibrary method.
If a static constructor throws an exception, the runtime will not invoke it a second time, and the
type will remain uninitialized for the lifetime of the application domain in which your program is
running.

Destructors (C# Programming Guide)


Destructors are used to destruct instances of classes.
Remarks
Destructors cannot be defined in structs. They are only used with classes.
A class can only have one destructor.
Destructors cannot be inherited or overloaded.
Destructors cannot be called. They are invoked automatically.
A destructor does not take modifiers or have parameters.
For example, the following is a declaration of a destructor for the class Car:
C#

Copy Code
class Car
{
~Car() // destructor
{
// cleanup statements...
}
}
The destructor implicitly calls Finalize on the base class of the object. Therefore, the previous
destructor code is implicitly translated to the following code:

Copy Code
protected override void Finalize()
{
try
{
// Cleanup statements...
}
finally
{
base.Finalize();
}
}
This means that the Finalize method is called recursively for all instances in the inheritance chain,
from the most-derived to the least-derived.
Note:
Empty destructors should not be used. When a class contains a destructor, an entry is created in
the Finalize queue. When the destructor is called, the garbage collector is invoked to process the
queue. If the destructor is empty, this just causes a needless loss of performance.
The programmer has no control over when the destructor is called because this is determined by
the garbage collector. The garbage collector checks for objects that are no longer being used by
the application. If it considers an object eligible for destruction, it calls the destructor (if any) and
reclaims the memory used to store the object. Destructors are also called when the program
exits.
It is possible to force garbage collection by calling Collect, but most of the time, this should be
avoided because it may create performance issues.
Using Destructors to Release Resources
In general, C# does not require as much memory management as is needed when you develop
with a language that does not target a runtime with garbage collection. This is because the .NET
Framework garbage collector implicitly manages the allocation and release of memory for your
objects. However, when your application encapsulates unmanaged resources such as windows,
files, and network connections, you should use destructors to free those resources. When the
object is eligible for destruction, the garbage collector runs the Finalize method of the object.
Explicit Release of Resources
If your application is using an expensive external resource, we also recommend that you provide
a way to explicitly release the resource before the garbage collector frees the object. You do this
by implementing a Dispose method from the IDisposable interface that performs the necessary
cleanup for the object. This can considerably improve the performance of the application. Even
with this explicit control over resources, the destructor becomes a safeguard to clean up
resources if the call to the Dispose method failed.

Forcing a Garbage Collection


The garbage collection GC class provides the GC.Collect method, which you can use to give your
application some direct control over the garbage collector. In general, you should avoid calling
any of the collect methods and allow the garbage collector to run independently. In most cases,
the garbage collector is better at determining the best time to perform a collection. In certain rare
situations, however, forcing a collection might improve your application's performance. It might be
appropriate to use the GC.Collect method in a situation where there is a significant reduction in
the amount of memory being used at a defined point in your application's code. For example, an
application might use a document that references a significant number of unmanaged resources.
When your application closes the document, you know definitively that the resources the
document has been using are no longer needed. For performance reasons, it makes sense to
release them all at once. For more information, see the GC.Collect Method.
Before the garbage collector performs a collection, it suspends all currently executing threads.
This can become a performance issue if you call GC.Collect more often than is necessary. You
should also be careful not to place code that calls GC.Collect at a point in your program where
users could call it frequently. This would defeat the optimizing engine in the garbage collector,
which determines the best time to run a garbage collection.

NET Framework Data Providers (ADO.NET)


A .NET Framework data provider is used for connecting to a database, executing commands, and
retrieving results. Those results are either processed directly, placed in a DataSet in order to be
exposed to the user as needed, combined with data from multiple sources, or remoted between
tiers. .NET Framework data providers are lightweight, creating a minimal layer between the data
source and code, increasing performance without sacrificing functionality.
The following table lists the data providers that are included in the .NET Framework.
.NET Framework data
provider Description
.NET Framework Data Provides data access for Microsoft SQL Server version 7.0 or later.
Provider for SQL Server Uses the System.Data.SqlClient namespace.
.NET Framework Data For data sources exposed by using OLE DB. Uses the
Provider for OLE DB System.Data.OleDb namespace.
.NET Framework Data For data sources exposed by using ODBC. Uses the
Provider for ODBC System.Data.Odbc namespace.
.NET Framework Data For Oracle data sources. The .NET Framework Data Provider for
Provider for Oracle Oracle supports Oracle client software version 8.1.7 and later, and
uses the System.Data.OracleClient namespace.
EntityClient Provider Provides data access for Entity Data Model (EDM) applications. Uses
the System.Data.EntityClient namespace.
Core Objects of .NET Framework Data Providers
The following table outlines the four core objects that make up a .NET Framework data provider.
Object Description
Connection Establishes a connection to a specific data source. The base class for all
Connection objects is the DbConnection class.
Command Executes a command against a data source. Exposes Parameters and can
execute in the scope of a Transaction from a Connection. The base class for all
Command objects is the DbCommand class.
DataReader Reads a forward-only, read-only stream of data from a data source. The base
class for all DataReader objects is the DbDataReader class.
DataAdapter Populates a DataSet and resolves updates with the data source. The base class
for all DataAdapter objects is the DbDataAdapter class.

Compilation of Dot Net code

Source code written in C# is compiled into an intermediate language (IL) that conforms to the CLI
specification. The IL code, along with resources such as bitmaps and strings, is stored on disk in
an executable file called an assembly, typically with an extension of .exe or .dll. An assembly
contains a manifest that provides information on the assembly's types, version, culture, and
security requirements.
When the C# program is executed, the assembly is loaded into the CLR, which might take
various actions based on the information in the manifest. Then, if the security requirements are
met, the CLR performs just in time (JIT) compilation to convert the IL code into native machine
instructions. The CLR also provides other services related to automatic garbage collection,
exception handling, and resource management.

Serialization. :

Serialization is the process of converting the state of an object into a form that can be persisted or
transported. The complement of serialization is deserialization, which converts a stream into an
object. Together, these processes allow data to be easily stored and transferred.
The .NET Framework features two serializing technologies:
Binary serialization preserves type fidelity, which is useful for preserving the state of an object
between different invocations of an application. For example, you can share an object between
different applications by serializing it to the Clipboard. You can serialize an object to a stream, to
a disk, to memory, over the network, and so forth. Remoting uses serialization to pass objects "by
value" from one computer or application domain to another.
XML serialization serializes only public properties and fields and does not preserve type fidelity.
This is useful when you want to provide or consume data without restricting the application that
uses the data. Because XML is an open standard, it is an attractive choice for sharing data
across the Web. SOAP is likewise an open standard, which makes it an attractive choice.
Delegates (C# Programming Guide)
A delegate is a type that references a method. Once a delegate is assigned a method, it behaves
exactly like that method. The delegate method can be used like any other method, with
parameters and a return value, as in this example:
C#

Copy Code
public delegate int PerformCalculation(int x, int y);
Any method that matches the delegate's signature, which consists of the return type and
parameters, can be assigned to the delegate. This makes is possible to programmatically change
method calls, and also plug new code into existing classes. As long as you know the delegate's
signature, you can assign your own delegated method.
This ability to refer to a method as a parameter makes delegates ideal for defining callback
methods. For example, a sort algorithm could be passed a reference to the method that
compares two objects. Separating the comparison code allows the algorithm to be written in a
more general way.
Delegates Overview
Delegates have the following properties:
Delegates are similar to C++ function pointers, but are type safe.
Delegates allow methods to be passed as parameters.
Delegates can be used to define callback methods.
Delegates can be chained together; for example, multiple methods can be called on a single
event.
Methods don't need to match the delegate signature exactly. For more information, see
Covariance and Contravariance
C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be
passed as parameters in place of a separately defined method.

Events (C# Programming Guide)


Events provide a way for a class or object to notify other classes or objects when something of
interest happens. The class that sends (or raises) the event is called the publisher and the
classes that receive (or handle) the event are called subscribers.
In a typical C# Windows Forms or Web application, you subscribe to events raised by controls
such as buttons and list boxes. You can use the Visual C# integrated development environment
(IDE) to browse the events that a control publishes and select the ones that you want to handle.
The IDE automatically adds an empty event handler method and the code to subscribe to the
event. For more information, see How to: Subscribe to and Unsubscribe from Events (C#
Programming Guide).
Events Overview
Events have the following properties:
The publisher determines when an event is raised; the subscribers determine what action is taken
in response to the event.
An event can have multiple subscribers. A subscriber can handle multiple events from multiple
publishers.
Events that have no subscribers are never called.
Events are commonly used to signal user actions such as button clicks or menu selections in
graphical user interfaces.
When an event has multiple subscribers, the event handlers are invoked synchronously when an
event is raised. To invoke events asynchronously, see Calling Synchronous Methods
Asynchronously.
Events can be used to synchronize threads.
In the .NET Framework class library, events are based on the EventHandler delegate and the
EventArgs base class.

Global Assembly Cache


Each computer where the common language runtime is installed has a machine-wide code cache
called the global assembly cache. The global assembly cache stores assemblies specifically
designated to be shared by several applications on the computer.
You should share assemblies by installing them into the global assembly cache only when you
need to. As a general guideline, keep assembly dependencies private, and locate assemblies in
the application directory unless sharing an assembly is explicitly required. In addition, it is not
necessary to install assemblies into the global assembly cache to make them accessible to COM
interop or unmanaged code.
Note:
There are scenarios where you explicitly do not want to install an assembly into the global
assembly cache. If you place one of the assemblies that make up an application in the global
assembly cache, you can no longer replicate or install the application by using the xcopy
command to copy the application directory. You must move the assembly in the global assembly
cache as well.
There are several ways to deploy an assembly into the global assembly cache:
Use an installer designed to work with the global assembly cache. This is the preferred option for
installing assemblies into the global assembly cache.
Use a developer tool called the Global Assembly Cache tool (Gacutil.exe), provided by the
Windows Software Development Kit (SDK).
Use Windows Explorer to drag assemblies into the cache.

Garbage Collection
The .NET Framework's garbage collector manages the allocation and release of memory for your
application. Each time you use the newoperator to create an object, the runtime allocates
memory for the object from the managed heap. As long as address space is available in the
managed heap, the runtime continues to allocate space for new objects. However, memory is not
infinite. Eventually the garbage collector must perform a collection in order to free some memory.
The garbage collector's optimizing engine determines the best time to perform a collection, based
upon the allocations being made. When the garbage collector performs a collection, it checks for
objects in the managed heap that are no longer being used by the application and performs the
necessary operations to reclaim their memory.
This section describes how the garbage collector automatically manages the allocation and
release of memory for the managed objects in your application. In addition, it describes the
recommended design pattern to use to properly clean up any unmanaged resources that your
application creates.

Anda mungkin juga menyukai