.NET Framework Class Library. Mark Sapossnek CS 594 Computer Science Department Metropolitan College Boston University. Prerequisites. This module assumes you understand the fundamentals of: Programming Variables Statements Functions Loops Object-oriented programming Classes
Une image / un lien ci-dessous est fourni (tel quel) pour télécharger la présentation
Politique de téléchargement : le contenu du site vous est fourni TEL QUEL pour votre information et votre usage personnel ; il ne peut être vendu, concédé sous licence ni partagé sur d’autres sites sans l’accord de son auteur.Le contenu vous est fourni TEL QUEL, pour votre information et votre usage personnel uniquement.Téléchargez la présentation en cliquant sur ce lien.Lors du téléchargement, si vous ne parvenez pas à télécharger une présentation, l’éditeur a peut-être supprimé le fichier de son serveur.Pendant le téléchargement, si vous ne parvenez pas à obtenir une présentation, le fichier a peut-être été supprimé par l’éditeur.
F I N
Plus de contenu associé
Transcription de la présentation
.NET Framework Class Library Mark SapossnekCS 594 Computer Science Department Metropolitan College Boston University
Prerequisites • This module assumes you understand the fundamentals of: • Programming • Variables • Statements • Functions • Loops • Object-oriented programming • Classes • Inheritance • Polymorphism • Members • C#
Learning Objectives • Gain an overview of various .NET Framework classes and interfaces • Be able to write programs using these classes and interfaces
Agenda • Introduction • System Namespace • Collection Classes • I/O and Networking • Threading and Synchronization • Transactions • Exceptions
Introduction • Looking Back • The Microsoft .NET Framework Class Library • Benefits of the .NET Framework Class Library
IntroductionLooking Back • Language-dependent runtime libraries • C Runtime Library • C++ Standard Template Library • Visual Basic Runtime • Discriminatory access to functionality • Many APIs unsupported by Visual Basic • Advanced tasks often require C/C++ • Core functionality scattered all over Windows • COM/COM+, ActiveX controls, System DLLs, SDKs, IE • Multi-language development was difficult • COM/COM+ Libraries were unorganized • Extending existing classes was difficult
Introduction.NET Framework Class Library • One-stop, well-organized class framework • O/S-independent subset submitted to ECMA • Standardization backed by Microsoft, HP, Intel • Subset includes most things covered here • http://msdn.microsoft.com/net/ecma/ • Integrates all current Windows technologies • Everything in one place – for all languages • Windows Forms, GDI+, printing for Windows development • Web Forms, Web Services, networking for web development • Supports Active Directory, WMI, MSMQ, Services
IntroductionBenefits • Cross-language interoperability • Simplifies multi-language development, effectively providing a common language API • Supplies a standard set of classes, interfaces, and structures for any language targeting .NET CLR • Consistent and unified programming model • Replaces many existing COM libraries • Object-oriented and extensible class library • Inheritance, polymorphism and method overloading • Abstract base classes, Interfaces
Agenda • Introduction • System Namespace • Collection Classes • I/O and Networking • Threading and Synchronization • Transactions • Exceptions
System Namespace • System.Object • The not-so-primitive "primitive" types • String and text classes • Dates, times, and calendars • System console support • Standard interfaces
System NamespaceNamespaces Example Namespace MyProject { using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; Using System.Data … Public class Form1 : Form … }
System NamespaceSystem.Object • Base class for each and every type • Inheritance from System.Object is typically implicit • All simple and complex types share the same base • Single base class makes framework consistent • Collection classes can be used for everything • Intrinsic model for handling variant types • Strongly typed--no pointers, no structures • Much less error-prone than COM's VARIANT type • System.Object is a reference type • Value types (internally) inherit from ValueType • Special class derived from Object
System NamespaceSystem.Object Methods • System.Object.Equals(Object o) • Test if two types are equal • System.Object.ReferenceEquals(Object o) • Test if two references are to the same object • System.Object.Finalize() • To be overridden by subclasses. • Called when object is garbage collected • System.Object.GetHashCode() • Used with System.Collections.HashTable • Should be overriden to return good hashes • Good hash distribution speeds up hash tables • Default implementation: identity-based hash
System NamespaceSystem.Object Methods • System.Object.GetType() • Retrieves the type object for the object's class • GetType() is the entry point for .NET Reflection • System.Object.MemberwiseClone() • Creates an exact clone of this object • Works through Reflection with any class • ToString() • To be overriden; returns text representation • Default returns qualified name of this class • Not designed for user messages (use IFormattable)
System NamespaceSystem.Object Examples Public class Person { String name; public override string ToString(){ return name; } } Name n1 = new Name(“Fred”); Name n2 = new Name(“Fred”); Name n3 = n2; //n2 & n3 point to the same object if (n1 == n2) … // false if (n2 == n3) … // true if (n1.Equals(n2)) … // true if (n2.Equals(n3)) … // true
System Namespace“Primitive” Types • Traditionally perceived as "magic" or "special" • There is no primitive-type magic in .NET! • Very Smalltalk-like model • "Primitive" types are regular framework types • Still exposed as language-intrinsic types • C#: bool, int, long, string, double, float... • Visual Basic.NET: Boolean, Integer, String... • "Primitives" are mostly value-types • Exception: System.String is reference type • "Primitive" Types are not so primitive anymore • Full-featured classes, rich functionality
System NamespaceSystem.String • System.String is the cross-language string • One storage method, one API, unified handling • Locale-aware, always Unicode • String is immutable • Methods that appear to modify a String actually construct a new one • Use String.Format or StringBuilder class instead of string concatenation • Strings can be interned • One standard copy is kept • Can compare references
System NamespaceSystem.String • Fully featured string-handling capabilities • Forward and reverse substring searches • IndexOf(), LastIndexOf(), StartsWith(), EndsWith() • Whitespace stripping and padding • Trim(), PadLeft(), PadRight() • Range manipulation and extraction • Insert(), Remove(), Replace(), Substring(), Join(), Split() • Character casing and advanced formatting • ToLower(), ToUpper() • Format() much like C's printf but safe
System NamespaceSystem.String Example // string comparison Public static int Main() { string s =“abc”; string s1; s1 = s; // s1 and s refer to the same object string s2 = “abc”; if (s1 == s2) Console.WriteLine(“Strings are equal”); else Console.WriteLine(“This shouldn’t happen!”); return 0 }
System NamespaceSystem.Text.StringBuilder • Efficient way to build up a string by concatenating, replacing, inserting and removing substrings • Automatically increases buffer size • Can control manually too
System NamespaceOther Core Types • System.Byte, System.SByte – Single byte numeric • System.Char – Single Unicode character • System.Boolean – True or False logical value • System.Guid • 128-bit, universally unique identifier • Built-in generator: System.Guid.NewGuid() • Intrinsic conversions to and from strings, byte arrays • The "Nothings" • System.DBNull – database-equivalent NULL type • System.Empty – like COM's VT_EMPTY • System.Missing – used with optional args
System NamespaceDate and Time Support • System.DateTime struct for dates and times • Virtually unlimited date values (100 AD to 9999 AD) • Date and Time arithmetics built-in • AddDays(), AddSeconds()... • Sophisticated, locale-aware formatting and parsing • System.TimeSpan struct for durations • Can represent arbitrary timespans • Can express span in aribitary units by conversion • System.TimeZone for time-zone support
System NamespaceSystem.Console • System.Console class for console I/O • Supports standard in, standard out, standard error • Writing to the console • Write() or WriteLine() • Supports String.Format syntax • Reading from the console • Read() reads on characters • ReadLine() reads one full line Console.Write("Snow White and the {0} dwarfs", 7);
System NamespaceOther System Goodies • System.URI class • Two-way parsing and construction of URIs • System.Random class • Random number generator • System.Convert class • One-stop place for core type conversions
System NamespaceStandard Interfaces • IFormattable: Provides functionality to format the value of an object • Format method: Formats the value of the current instance as specified. • IDisposable: Provides explicit control of releasing resources
System NamespaceString.Format and IFormattable • String.Format • Implement IFormattable for custom formatting of your own types • Use IServiceProvider to get culturally-aware delimiters for numbers and date/time • Implement ICustomFormatter to override default formatting for built-in types String.Format(“Please order {0} widgets at {1} each.”, i, f); String.Format(“{0:U}”, DateTime.Now); interface IFormattable { String Format(String format, IServiceObjectProvider sop);}
System NamespaceIDisposable Example class ResourceWrapper : IDisposable { private IntPrt handle; // Pointer to an external resourceprivate OtherResource otherRes; bool disposed = false; private void freeState () { // Free your own state if (!disposed) { CloseHandle (handle); dispose = true; } } // Free your own state, call dispose on all state you hold, // and take yourself off the Finalization queue public void Dispose () { freeState(); OtherRes.Dispose(); GC.Suppress.Finalization(this); } // Free your own state (NOT other state you hold) and // give your parent a chance to finalize public void Finalize () { freeState(); Base.Finalize(); }
Agenda • Introduction • System Namespace • Collection Classes • I/O and Networking • Threading and Synchronization • Transactions • Exceptions
Collection ClassesArrays • The only collection outside Collections namespace • System.Array class • Mapped to language-intrinsic arrays • Polymorphic, stores System.Object elements • Arbitrary number of dimensions, lengths • Specified at creation time (CreateInstance) • After construction, array dimensions are fixed • Supports sorting • Self-comparing IComparable objects • External comparisons with IComparer • Supports binary searches on sorted arrays
Collection ClassesArrays Example public static void Main() { // Create and initialize a new int array and a new Object array. int[] myIntArray = new int[5] { 1, 2, 3, 4, 5 }; Object[] myObjArray = new Object[5] { 26, 27, 28, 29, 30 }; // Copy the first two elements from the int array to the Object array. Array.Copy( myIntArray, myObjArray, 2 ); // Print the values of the modified arrays. Console.WriteLine( "\nAfter copying the first two elements of the int array to the Object array," ); Console.Write( "int array: " ); PrintValues( myIntArray ); Console.Write( "Object array:" ); PrintValues( myObjArray ); // Copy the last two elements from the Object array to the int array. Array.Copy( myObjArray, myObjArray.GetUpperBound(0) - 1, myIntArray, myIntArray.GetUpperBound(0) - 1, 2 ); }
Collection ClassesCollections Interfaces • IEnumerable • Supports simple iteration over the collection • GetEnumerator() returns IEnumerator iterator • IEnumerator: Current, MoveNext(), Reset() • IEnumerator • Iterator for enumerable collections • Properties and methods: Current(), MoveNext(), Reset()
Collection ClassesEnumerating a Set of Items • All types offer standard mechanism for item iteration • System.Collections.IEnumerable interface • GetEnumerator returns object dedicated to item iteration public interface IEnumerable { IEnumerator GetEnumerator();} public interface IEnumerator { Boolean MoveNext(); Object Current { get; } void Reset();}
Collection ClassesIEnumerable and IEnumerator // Construct a type that manages a set of items// This type must offer a public GetEnumerator methodSetType st = new SetType(...);// To enumerate items, request the enumeratorIEnumerator e = st.GetEnumerator();// Advance enumerator’s cursor until no more itemswhile (e.MoveNext()) { // Cast the Current item to the proper type ItemType it = (ItemType) e.Current; // Use the item any way you want Console.WriteLine(“Do something with this item: “ + it);}
Collection ClassesCollections Interfaces • ICollection (derived from IEnumerable) • Basic collection interface: Count(), CopyTo(), IsSynchronized() • IDictionary (derived from ICollection) • Basic association container interface • Keys / Values table implementation • Item indexer looks up a value given its key • Add(), Remove(), Contains() and Clear() methods • IList (derived from ICollection) • A collection whose objects can be individually indexed • Item indexer looks up a value given its index • Add(), Remove(), Contains() and Clear() methods
Collection ClassesCollection Classes • System.Collections.ArrayList • Dynamic arrays implementing IList • Can grow and shrink in size (unlike System.Array) • System.Collections.BitArray • Compact array of bits • System.Collections.HashTable • Fast hash-table implementing IDictionary • Uses HashCode of object • There is no Dictionary class; use HashTable • System.Collections.SortedList • Auto-sorted, string- and integer- indexed collection • No duplicates
Collection ClassesSystem.Collections.ArrayList using System; using System.Collections; public class SampleArrayList { public static void Main() { // Create and initialize a new ArrayList. ArrayList myAL = new ArrayList(); myAL.Add("Hello"); myAL.Add("World"); myAL.Add("!"); // Display the properties and values. Console.WriteLine( "myAL" ); Console.WriteLine( "\tCount: {0}", myAL.Count ); Console.WriteLine( "\tCapacity: {0}", myAL.Capacity ); Console.Write( "\tValues:" ); PrintValues( myAL );} public static void PrintValues( IEnumerable myList ) { System.Collections.IEnumerator myEnumerator = myList.GetEnumerator(); while ( myEnumerator.MoveNext() ) Console.Write("\t{0}", myEnumerator.Current ); Console.WriteLine(); } }
Collection ClassesOther Collection Classes • System.Collections.Stack • Stack implementation with Push() and Pop() • Fully enumerable (implements IEnumerable) • System.Collections.Queue • Queue with Dequeue() and Enqueue() • Fully enumerable
Collection ClassesSystem.Collections.Stack using System; using System.Collections; public class SamplesStack { public static void Main() { // Create and initialize a new Stack. Stack myStack = new Stack(); myStack.Push("Hello"); myStack.Push("World"); myStack.Push("!"); Console.WriteLine( "myStack" ); Console.WriteLine( "\tCount: {0}", myStack.Count ); Console.Write( "\tValues:" ); PrintValues( myStack ); } public static void PrintValues( IEnumerable myCollection ) { System.Collections.IEnumerator myEnumerator = myCollection.GetEnumerator(); while ( myEnumerator.MoveNext() ) Console.Write( "\t{0}", myEnumerator.Current ); Console.WriteLine(); } }
Collection ClassesSystem.Collections.Queue using System; using System.Collections; public class SamplesQueue { public static void Main() { Queue myQ = new Queue(); myQ.Enqueue("Hello"); myQ.Enqueue("World"); myQ.Enqueue("!"); Console.WriteLine( "myQ" ); Console.WriteLine( "\tCount: {0}", myQ.Count ); Console.Write( "\tValues:" ); PrintValues( myQ ); } public static void PrintValues( Ienumerable myCollection ) { System.Collections.IEnumerator myEnumerator = myCollection.GetEnumerator(); while ( myEnumerator.MoveNext() ) Console.Write( "\t{0}", myEnumerator.Current ); Console.WriteLine(); } }
Collection ClassesSystem.Collections.Specialized • NameObjectCollectionBase • Abstract class, indexed view on HashTable • Combines indexed order with Hashtable-speed • NameValueCollection • Sorted collection of string values and string keys • StringDictionary • Unsorted, string values and string keys
Agenda • Introduction • System Namespace • Collection Classes • I/O and Networking • Threading and Synchronization • Transactions • Exceptions
I/O and Networking • Directories and Files • Streams, Stream Readers and Stream Writers • Networking Support
I/O and NetworkingDirectories and Files • Provides a fully object-oriented way to explore the file system • System.IO.Directory and System.IO.File provide static methods to manipulate directories and files, respectively • System.IO.DirectoryInfo and System.IO.FileInfo provide instance methods to manipulate directories and files, respectively
I/O and NetworkingDirectories and Files • System.IO.DirectoryInfo represents a directory • GetDirectories([mask]) gets subdirectories • GetFiles([mask]) gets contained files • System.IO.FileInfo represents a file • Can construct directly by providing a path • Or returned from GetFiles() enumeration • All OpenX() methods return System.IO.Stream • Open(), OpenRead(), OpenWrite(), OpenText()
I/O and NetworkingStreams • Abstract base stream: System.IO.Stream • Read(), Write() for basic synchronous access • Full asynchronous support • Call BeginRead() or BeginWrite() and pass callback • Callback is invoked as soon as data is received. • Asynchronous call completed with EndRead()/EndWrite() • System.IO.FileStream • Can open and access files directly • Actual type returned by File.Open() • System.IO.MemoryStream • Constructs a stream in-memory
I/O and NetworkingStream Readers • Higher level access to Stream reading functions • System.IO.BinaryReader • Designed for typed access to stream contents • Read methods for most core data types • ReadInt16(), ReadBoolean(), ReadDouble(), etc. • System.IO.TextReader • Abstract base class for reading strings from streams • System.IO.StreamReader (inherits TextReader) • ReadLine() reads to newline • ReadToEnd() reads full stream into string • System.IO.StringReader (inherits TextReader) • Simulates stream input from string
I/O and NetworkingStream Writers • High-level access to Stream writing functions • System.IO.BinaryWriter • Designed for typed writes to streams • >15 strongly typed overloads for Write() method • System.IO.TextWriter • Abstract base class for writing strings to streams • Includes placeholder-formatted strings • System.IO.StreamWriter (inherits TextWriter) • Writes strings to streams with encoding support • System.IO.StringWriter • Simulates streams--writes on an output string
I/O and NetworkingStream Reader Example // Reading Text Files File fIn = NewFile(“C:\\dotNet Projects\\Readme.txt”); StreamRead strm = fIn.OpenText(); String sLine; do { sLine = strm.ReadLine(); AddItem(sLine); } while (sLine != null); Strm.close();
I/O and NetworkingStream Writer Example public class MyWriter { private Stream s; public MyWriter(Stream stream) { s = stream; } public void WriteDouble(double myData) { byte[] b = myData.GetBytes(); // GetBytes is a binary representation of // a double data type. s.Write(b,0,b.Length); } public void Close() { s.Close(); } }
Connexion au compte
Connectez-vous pour publier votre contenu sur SlideServe.