Indexación

26. April 2008 04:27 by Oscar S.S. in Lenguajes  //  Tags:   //   Comments (0)

Antes de comenzar hablar directamente de los indizadores, vamos a ver unos ejemplos que nos ayudarán a comprender mejor las ventajas del uso de la indexación.

Supongamos que tenemos una clase llamada “Personas” que lo único que hace es guardar los nombres de distintas personas. Parece lógico que para implementar esta clase definamos una matriz de tipo String que almacene los nombres. Por ejemplo podríamos pensar en hacer esto:


    class Personas
    {
        
public string[] Nombre = new string[3];
    
}

Así tenemos definida una clase que almacena 3 nombres de personas en una matriz de tipo String. Para utilizar solo tendríamos que hacer esto:


static void Main(string[] args)
       {
           Personas persona 
= new Personas();
           
//Rellenamos la matriz.
            
persona.Nombre[0"Mariano";
           
persona.Nombre[1"Pedro";
           
persona.Nombre[2"Maria";

           
//Mostrar el contenido de la matriz.
            
foreach (string item in persona.Nombre)
               Console.WriteLine(item)
;

           
Console.ReadLine();
       
}

Desde luego esto funciona pero al tener declarada la matriz como pública no contribuimos a proteger debidamente los miembros de la clase.

Una solución a este problema de proteger los miembros es declararlos como privados. Es decir:


    class Personas
    {
       
private string[] Nombre = new string[3];
    
}

¿Cómo accedemos ahora a los elementos de la matriz “persona”?. Al estar declarada como privada no tenemos acceso a este campo por medio de un objeto de la clase “Personas”.

La solución es muy sencilla. Añadimos a nuestra clase dos métodos públicos, una para asignar nombres en la matriz (método Añadir) y otro para recuperar los valores de los elementos almacenados en la matriz (método Obtener).


    class Personas
    {
        
private string[] Nombre = new string[3];

        public void 
Añadir(string nom, int i)
        {
            Nombre[i] 
nom;
        
}

        
public string Obtener(int i)
        {
            
return Nombre[i];
        
}
    }

Ahora la clase podemos utilizarla por medio de los métodos de la siguiente forma.


            Personas persona = new Personas();
            
//Rellenamos la matriz.
            
persona.Añadir("Mariano"0);
            
persona.Añadir("Pedro"1);
            
persona.Añadir("Maria"2);

            
//Mostrar el contenido de la matriz.
            
for (int 0i < 3i++)
                Console.WriteLine(persona.Obtener(i))
;

            
Console.ReadLine();

Es perfecto. Todo funciona correctamente y tenemos el nivel de protección que deseábamos.

Sin embargo no estamos utilizando la matriz como si fuera una matriz. No accedemos a los elementos por medio de un índice dentro del operador de indexación [] que tantas veces hemos visto en las matrices. Hagamos lo siguiente:


    class Personas
    {
        
private string[] Nombre = new string[3];

        public string this
[int i]
        {
            
get return Nombre[i]}
            
set { Nombre[i] = value; }
        }
    }

La forma de utilizar un objeto de clase “Personas”, ahora que ya esta indexada, es la siguiente:


            Personas persona = new Personas();
            
//Rellenamos la matriz.
            
persona[0"Mariano";
            
persona[1"Pedro";
            
persona[2"Maria";

            
//Mostrar el contenido de la matriz.
            
for (int 0i < 3i++)
                Console.WriteLine(persona[i])
;

            
Console.ReadLine();

Como vemos la definición de la clase tiene mucho menos código al no tener que implementar dos métodos, esto ya es una ventaja. La forma de obtener y establecer los elementos de la matriz es mucho más natural.

Si una propiedad es una especie de “método inteligente” de las variables definidas en una clase. La indexación es “método inteligente” de las matrices definidas en nuestras clases.

No lo dudéis, si tenéis una clase con varios campos que almacenan datos en matrices, ¡indexar la clase!.

 

1- Desarrollando aplicaciones que usen tipos y colecciones System.

12. April 2008 10:51 by Oscar.SS in Certificaciones, Desarrollo .NET  //  Tags: ,   //   Comments (0)

A- Manage data in a .NET Framework application by using the .NET Framework 2.0 system types. (Refer System namespace)

Value types

Nullable type

Reference types

Attributes

Generic types

Exception classes

Boxing and UnBoxing

TypeForwardedToAttribute Class

 


B- Manage a group of associated data in a .NET Framework application by using collections. (Refer System.Collections namespace)

ArrayList class

Collection interfaces

ICollection interface and IList interface

IComparer interface and IEqualityComparer interface

IDictionary interface and IDictionaryEnumerator interface

IEnumerable interface and IEnumerator interface

Iterators

Hashtable class

CollectionBase class and ReadOnlyCollectionBase class

DictionaryBase class and DictionaryEntry class

Comparer class

Queue class

SortedList class

BitArray class

Stack class

 


C- Improve type safety and application performance in a .NET Framework application by using generic collections. (Refer System.Collections.Generic namespace)

Collection.Generic interfaces

Generic IComparable interface (Refer System Namespace)

Generic ICollection interface and Generic IList interface

Generic IComparer interface and Generic IEqualityComparer interface

Generic IDictionary interface

Generic IEnumerable interface and Generic IEnumerator interface IHashCodeProvider interface

Generic Dictionary

Generic Dictionary class and Generic Dictionary.Enumerator structure

Generic Dictionary.KeyCollection class and Dictionary.KeyCollection.Enumerator structure

Generic Dictionary.ValueCollection class and Dictionary.ValueCollection.Enumerator structure

Generic Comparer class and Generic EqualityComparer class

Generic KeyValuePair structure

Generic List class, Generic List.Enumerator structure, and Generic SortedList class

Generic Queue class and Generic Queue.Enumerator structure

Generic SortedDictionary class

Generic LinkedList

Generic LinkedList class

Generic LinkedList.Enumerator structure

Generic LinkedListNode class

Generic Stack class and Generic Stack.Enumerator structure


D- Manage data in a .NET Framework application by using specialized collections. (Refer System.Collections.Specialized namespace)

Specialized String classes

StringCollection class

StringDictionary class

StringEnumerator class

Specialized Dictionary

HybridDictionary class

IOrderedDictionary interface and OrderedDictionary class

ListDictionary class

Named collections

NameObjectCollectionBase class

NameObjectCollectionBase.KeysCollection class

NameValueCollection class

CollectionsUtil

BitVector32 structure and BitVector32.Section structure


E- Implement .NET Framework interfaces to cause components to comply with standard contracts. (Refer System namespace)

IComparable interface

IDisposable interface

IConvertible interface

ICloneable interface

IEquatable interface

IFormattable interface

 


F- Control interactions between .NET Framework application components by using events and delegates. (Refer System namespace)

Delegate class

EventArgs class

EventHandler delegates

2- Implementando servicios, procesos, y dominios de aplicación en una aplicación de la plataforma .NET.

12. April 2008 10:49 by Oscar.SS in Certificaciones, Desarrollo .NET  //  Tags: ,   //   Comments (0)

A- Implement, install, and control a service. (Refer System.ServiceProcess namespace)

Inherit from ServiceBase class

ServiceController class and ServiceControllerPermission class

ServiceInstaller and ServiceProcessInstaller class

SessionChangeDescription structure and SessionChangeReason enumeration

 

 

B- Develop multithreaded .NET Framework applications. (Refer System.Threading namespace)

Thread class

ThreadPool class

ThreadStart delegate and ParameterizedThreadStart delegate

Timeout class, Timer class, TimerCallback delegate, WaitCallback delegate, WaitHandle class, and WaitOrTimerCallback delegate

ThreadState enumeration and ThreadPriority enumeration

ReaderWriterLock class

AutoResetEvent class and ManualResetEvent class

IAsyncResult interface (Refer System namespace)

EventWaitHandle class, RegisterWaitHandle class, SendOrPostCallback delegate, and IOCompletionCallback delegate

Interlocked class

ExecutionContext class, HostExecutionContext class, HostExecutionContext Manager class, and ContextCallback delegate

LockCookie structure, Monitor class, Mutex class, and Semaphore class


C- Create a unit of isolation for common language runtime in a .NET Framework application by using application domains. (Refer System namespace)

Create an application domain.

Unload an application domain.

Configure an application domain.

Retrieve setup information from an application domain.

Load assemblies into an application domain.

3- Agregando configuración, diagnóstico, gestión, e instalación en una aplicación de la plataforma .NET.

12. April 2008 10:48 by Oscar.SS in Certificaciones, Desarrollo .NET  //  Tags: ,   //   Comments (0)

A- Embed configuration management functionality into a .NET Framework application. (Refer System.Configuration namespace)

Configuration class and ConfigurationManager class

ConfigurationElement class, ConfigurationElementCollection class, and ConfigurationElementProperty class

ConfigurationSection class, ConfigurationSectionCollection class, ConfigurationSectionGroup class, and ConfigurationSectionGroupCollection class

Implement ISettingsProviderService interface

Implement IApplicationSettingsProvider interface

ConfigurationValidatorBase class

 

 

B- Create a custom Microsoft Windows Installer for the .NET Framework components by using the System.Configuration.Install namespace, and configure the .NET Framework applications by using configuration files, environment variables, and the .NET Framework Configuration tool (Mscorcfg.msc).

Installer class

Configure which runtime version a .NET Framework application should use.

Configure where the runtime should search for an assembly.

Configure the location of an assembly and which version of the assembly to use.

Direct the runtime to use the DEVPATH environment variable when you search for assemblies.

AssemblyInstaller class

ComponentInstaller class

Configure a .NET Framework application by using the .NET Framework Configuration tool (Mscorcfg.msc).

ManagedInstallerClass class

InstallContext class

InstallerCollection class

InstallEventHandler delegate

Configure concurrent garbage collection.

Register remote objects by using configuration files.


C- Manage an event log by using the System.Diagnostics namespace.

Write to an event log.

Read from an event log.

Create a new event log.


D- Manage system processes and monitor the performance of a .NET Framework application by using the diagnostics functionality of the .NET Framework 2.0. (Refer System.Diagnostics namespace)

Get a list of all running processes.

Retrieve information about the current process.

Get a list of all modules that are loaded by a process.

PerformanceCounter class, PerformanceCounterCategory, and CounterCreationData class

Start a process both by using and by not using command-line arguments.

StackTrace class

StackFrame class

 

 

E- Debug and trace a .NET Framework application by using the System.Diagnostics namespace.

Debug class and Debugger class

Trace class, CorrelationManager class, TraceListener class, TraceSource class, TraceSwitch class, XmlWriterTraceListener class, DelimitedListTraceListener class, and EventlogTraceListener class

Debugger attributes

DebuggerBrowsableAttribute class

DebuggerDisplayAttribute class

DebuggerHiddenAttribute class

DebuggerNonUserCodeAttribute class

DebugeerStepperBoundaryAttribute class

DebuggerStepThroughAttribute class

DebuggerTypeProxyAttribute class

DebuggerVisualizerAttribute class

 

 

F- Embed management information and events into a .NET Framework application. (Refer System.Management namespace)

Retrieve a collection of Management objects by using the ManagementObjectSearcher class and its derived classes.

Enumerate all disk drivers, network adapters, and processes on a computer.

Retrieve information about all network connections.

Retrieve information about all services that are paused.

ManagementQuery class

EventQuery class

ObjectQuery class

Subscribe to management events by using the ManagementEventWatcher class.

4- Implementando serializacion y la funcionalidad de entrada/salida en una aplicación de la plataforma .NET.

12. April 2008 10:45 by Oscar.SS in Certificaciones, Desarrollo .NET  //  Tags: ,   //   Comments (0)

A- Serialize or deserialize an object or an object graph by using runtime serialization techniques. (Refer System.Runtime.Serialization namespace)

Serialization interfaces

IDeserializationCallback interface

IFormatter interface and IFormatterConverter interface

ISerializable interface

Serilization attributes

OnDeserializedAttribute class and OnDeserializingAttribute class

OnSerializedAttribute class and OnSerializingAttribute class

OptionalFieldAttribute class

SerializationEntry structure and SerializationInfo class

ObjectManager class

Formatter class, FormatterConverter class, and FormatterServices class

StreamingContext structure

 

 

B- Control the serialization of an object into XML format by using the System.Xml.Serialization namespace.

Serialize and deserialize objects into XML format by using the XmlSerializer class.

Control serialization by using serialization attributes.

Implement XML Serialization interfaces to provide custom formatting for XML serialization.

Delegates and event handlers are provided by the System.Xml.Serialization namespace.


C- Implement custom serialization formatting by using the Serialization Formatter classes.

SoapFormatter class (Refer System.Runtime.Serialization.Formatters.Soap namespace)

BinaryFormatter class (Refer System.Runtime.Serialization.Formatters.Binary namespace)


D- Access files and folders by using the File System classes. (Refer System.IO namespace)

File class and FileInfo class

Directory class and DirectoryInfo class

DriveInfo class and DriveType enumeration

FileSystemInfo class and FileSystemWatcher class

Path class

ErrorEventArgs class and ErrorEventHandler delegate

RenamedEventArgs class and RenamedEventHandler delegate


E- Manage byte streams by using Stream classes. (Refer System.IO namespace)

FileStream class

Stream class

MemoryStream class

BufferedStream class

 

 

F- Manage the .NET Framework application data by using Reader and Writer classes. (Refer System.IO namespace)

StringReader class and StringWriter class

TextReader class and TextWriter class

StreamReader class and StreamWriter class

BinaryReader class and BinaryWriter class


G- Compress or decompress stream information in a .NET Framework application (refer System.IO.Compression namespace), and improve the security of application data by using isolated storage. (Refer System.IO.IsolatedStorage namespace)

IsolatedStorageFile class

IsolatedStorageFileStream class

DeflateStream class

GZipStream class

Recent Comments

Comment RSS

Month List