Sie sind auf Seite 1von 71

Chapter 3: Object-Based Programing

Hoang Anh Viet


VietHA@it-hut.edu.vn

HaNoi University of Technology


1

Overview
Everything is an object! At least, that is the view from inside the CLR and the C# programming language. This is no surprise, because C# is, after all, an objectoriented language. The objects that you create through class definitions in C# have all the same capabilities as the other predefined objects in the system

Apress-Accelerated C# 2008

Microsoft

Roadmap
3.1. Introduction 3.2. Implementing a time Abstract DataType with a class 3.3. Class Scope 3.4. Controlling Access to Members 3.5. Initialize Class Objects: Constructors 3.6.Using Overloaded Constructors 3.7. Properties 3.8. Composition: Objects References as Instance Variables of Other Classes

Microsoft

Roadmap(2)
3.9. Using the this Reference 3.10. Garbage Collection 3.11. static Class Members 3.12. const and readonly Members 3.13. Indexers 3.14. Data Abstaction and Information Hiding 3.15. Software Reusability 3.16. Namespace and Assemplies

Microsoft

3.1. Introduction

Object orientation uses classes to encapsulate data( attributes) and methods(behaviors)

Data members: member variables or instance variables Methods: manipulate the data

Objects are instantiated from classes Objects have the ability to hide their implementation from other objects( information hiding) Some objects can communicate with one another across welldefined interfaces

Example:

The drivers interface to a car includes steering wheel, accelerator pedal, brake pedal and gear shift

Microsoft

Roadmap

3.1. Introduction 3.2. Implementing a time Abstract DataType with a class 3.3. Class Scope 3.4. Controlling Access to Members 3.5. Initialize Class Objects: Constructors 3.6.Using Overloaded Constructors 3.7. Properties 3.8. Composition: Objects References as Instance Variables of Other Classes

Microsoft

3.2. Implimenting a Time Abstract DataType with a class


Classes in C# facilitate the creation of abstract data types(ADT), hiding their implementation from clients In procedural programming language: client code is dependent on implementation details of the data used in the code, ADTs eliminate this problem. Example:

Time1 class Three in instance variables: hour, minute and second A constructor: initialzes objects of Time1 class Method SetTime(): sets the time Method ToUniversalString(): returns a string in universal-time format Method ToStandardString(): returns a string in standard-time format

Microsoft

Example
// Class Time1 maintains time in 24-hour format. using System; // Time1 class definition public class Time1 : Object { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59 // Time1 constructor initializes instance variables to // zero to set default time to midnight public Time1() { SetTime( 0, 0, 0 ); } // Set new time value in 24-hour format. Perform validity // checks on the data. Set invalid values to zero. public void SetTime( int hourValue, int minuteValue, int secondValue ) { hour = ( hourValue >= 0 && hourValue < 24 ) ? hourValue : 0; minute = ( minuteValue >= 0 && minuteValue < 60 ) ? minuteValue : 0; second = (secondValue >= 0 && secondValue < 60) ? secondValue : 0; } // end method SetTime // convert time to universal-time (24 hour) format string public string ToUniversalString() { return String.Format( "{0:D2}:{1:D2}:{2:D2}", hour, minute, second); } // convert time to standard-time (12 hour) format string public string ToStandardString() { return String.Format("{0}:{1:D2}:{2:D2} {3}", ((hour == 12 || hour == 0) ? 12 : hour % 12), minute, second, (hour < 12 ? "AM" : "PM")); } } // end class Time1

Class Time1 inherits from class Object

Delicate the body of class

Declare variables

Constructor

Member Access Modifiers

Methods

Example
// Demonstrating class Time1. using System; using System.Windows.Forms; // TimeTest1 uses creates and uses a Time1 object class TimeTest1 { // main entry point for application static void Main( string[] args ) { Time1 time = new Time1(); // calls Time1 constructor string output; // assign string representation of time to output output = "Initial universal time is: " + time.ToUniversalString() + "\nInitial standard time is: " + time.ToStandardString(); // attempt valid time settings time.SetTime( 13, 27, 6 ); // append new string representations of time to output output += "\n\nUniversal time after SetTime is: " + time.ToUniversalString() + "\nStandard time after SetTime is: " + time.ToStandardString(); // attempt invalid time settings time.SetTime( 99, 99, 99 ); output += "\n\nAfter attempting invalid settings: " + "\nUniversal time: " + time.ToUniversalString() + "\nStandard time: " + time.ToStandardString(); MessageBox.Show(output, "Testing Class Time1"); } // end method Main } // end class TimeTest1

Roadmap

3.1. Introduction 3.2. Implementing a time Abstract DataType with a class 3.3. Class Scope 3.4. Controlling Access to Members 3.5. Initialize Class Objects: Constructors 3.6.Using Overloaded Constructors 3.7. Properties 3.8. Composition: Objects References as Instance Variables of Other Classes

Microsoft 10

3.3. Class Scope


A classs instance variables and methods belong to that classs scope Class members are accessible to methods in that classs scope and can be referenced by name Acesses to class members outside: referenceName.memberName Block scope:

Variables declared in a method have block scope If a block-scope variable has the same name to a class-scope variable, the class-scope one is hiden( access to that one in the method using keyword this and dot operator)

Microsoft 11

Roadmap
3.1. Introduction 3.2. Implementing a time Abstract DataType with a class 3.3. Class Scope 3.4. Controlling Access to Members 3.5. Initialize Class Objects: Constructors 3.6.Using Overloaded Constructors 3.7. Properties 3.8. Composition: Objects References as Instance Variables of Other Classes

Microsoft 12

3.4. Controlling Access to Members


The visibility of the member is defined by accessibility keyword The most common accessibility

Property

public: Public members are visible inside and outside of the class private: The visibility of private members is restricted to the containing class

Controls access to private data get and set properties

Microsoft 13

// Demonstrate compiler errors from attempt to access // private class members. public class Time1 : Object class RestrictedAccess { { private int hour; // main entry point for application private int minute; static void Main(string[] args) private int second; { } Time1 time = new Time1(); time.hour = 7; Compiler errors time.minute = 15; time.second = 30; } } // end class RestrictedAccess

Microsoft 14

Roadmap

3.1. Introduction 3.2. Implementing a time Abstract DataType with a class 3.3. Class Scope 3.4. Controlling Access to Members 3.5. Initialize Class Objects: Constructors 3.6.Using Overloaded Constructors 3.7. Properties 3.8. Composition: Objects References as Instance Variables of Other Classes

Microsoft 15

3.5. Initialize Class Objects: Constructors


Are called when a class is first loaded by the CLR of an object is created Set up the state of the object by initializing the fields to a desired predefined state Constructor syntax: accessibility modifier typename(parameterlist) Have the same name of the class and never have a return type Initialize the state of an object Types of Constructor: Called when an instance of a class is created Can be overloaded Default constructor:

Static Constructor Instance Constructor

If a class does not define any constructors, the compiler provides a default( no-argument) constructor( no code and noparameters) Can be provided by the programmer. Programmer-provided ones can have code in bodies

Microsoft 16

static Constructors

static constructors is used to initialize the values of static data when the value isnt known at comple time A given class (or structure) may define only a single static constructor.

A static constructor does not take an access modifier and cannot take any parameters.
A static constructor executes exactly one time, regardless of how many objects of the type are created. The runtime invokes the static constructor when it creates an instance of the class or before accessing the first static member invoked by the caller.

The static constructor executes before any instance-level constructors.

Microsoft 17

class Car { // The 'state' of the Car. public string petName; public int currSpeed; // A custom default constructor. public Car() { petName = "Chuck"; currSpeed = 10; } // Here, currSpeed will receive the // default value of an int (zero). public Car(string pn) { petName = pn; } // Let caller set the full 'state' of the Car. public Car(string pn, int cs) { petName = pn; currSpeed = cs; } .. }

A custom default constructor

static void Main(string[] args) { // Make a Car called Chuck going 10 MPH. Car chuck = new Car(); chuck.PrintState(); // Make a Car called Mary going 0 MPH. Car mary = new Car("Mary"); mary.PrintState(); // Make a Car called Daisy going 75 MPH. Car daisy = new Car("Daisy", 75); daisy.PrintState(); }

Instance Constructors

Microsoft 18

class SavingsAccount { public double currBalance; public static double currInterestRate; public SavingsAccount(double balance) { currBalance = balance; } // A static constructor. static SavingsAccount() { Console.WriteLine("In static ctor!"); currInterestRate = 0.04; } ... }

static Constructor

static Data

Microsoft 19

Roadmap

3.1. Introduction 3.2. Implementing a time Abstract DataType with a class 33. Class Scope 3.4. Controlling Access to Members 3.5. Initialize Class Objects: Constructors 3.6.Using Overloaded Constructors 3.7. Properties 3.8. Composition: Objects References as Instance Variables of Other Classes

Microsoft 20

3.6. Using Overloaded Constructors

Constructors can be overloaded Overloaded constructors may be used to provide different ways to initialize objects of a class Contructors overloading is the process of using the same Contructors name for multiple Contructors The function resolution of overloaded constructors is determined by the parameters of the new statement

Microsoft 21

Note:

If multiple contractor match a contractor call, the compiler picks the best match If none matches exactly but some implicit conversion can be done to match a contractor, then the contractor is invoked with implicit conversion. A constructor can call another constructor using the this reference

Microsoft 22

using System; Call Employee(string _name) constructor namespace Donis.CSharpBook using the colon syntax { public class Employee { public Employee(string _name) { name = _name; } Overloaded public Employee(string _first, string _last) Constructures { name = _first + " " + _last; } private string name = ""; } public class Personnel { public static void Main() { Employee bob = new Employee("Jim", "Wilson"); // 2 arg c'tor } } }

class Employee { public Employee() : this("") { } public Employee(string _name) { name = _name; } public Employee(string _first, string _last) : this(_first + " " + _last) { } public void GetName() { Console.WriteLine(name); } private string name = ""; }

Microsoft 23

Roadmap

3.1. Introduction 3.2. Implementing a time Abstract DataType with a class 3.3. Class Scope 3.4. Controlling Access to Members 3.5. Initialize Class Objects: Constructors 3.6.Using Overloaded Constructors 3.7. Properties 3.8. Composition: Objects References as Instance Variables of Other Classes

Microsoft 24

3.7. Properties

Used for strict control of access to the internal state of an object Are get and set methods exposed as properties Propertiy syntax:

Accessibility modifier type propertyname{ attributes get{getbody} attributes set{setbody}} Example:

Neither method is called directly Auto-Implemented Properties


C# 3.0 has a new feature called auto-implemented properties that reduce this burden significantly.

Microsoft 25

Example
using System; namespace Donis.CSharpBook { public class Person { private int prop_age; age property public int age { set { // perform validation prop_age=value; } get { return prop_age; } value keyword represents the implied parameter } } class People { public static void Main() { Person bob = new Person(); bob.age = 30; } Console.WriteLine(bob.age); Set method

Use Ato-Implemented Proerties

} }

// use Auto-Implemented Properties public class Employee { public string FullName { get; set; } public string Id { get; set; } }

Call gets method

Read-only and write-only properties


Read-only property:

Offer only the get method and omit the set method
Have a set only Password property ( write-only property)
public class SensitiveForm { private string prop_password; public string password { set { prop_password = value; } } }

Write-only property:

Example:

Microsoft 27

Roadmap

3.1. Introduction 3.2. Implementing a time Abstract DataType with a class 3.3. Class Scope 3.4. Controlling Access to Members 3.5. Initialize Class Objects: Constructors 3.6.Using Overloaded Constructors 3.7. Properties 3.8. Composition: Objects References as Instance Variables of Other Classes

Microsoft 28

3.8. Composition: Objects References as Instance Variables of Other Classes

One form of software reuse is composition, in which a class has as members references to objects of other classes. Example:

Microsoft 29

Class Date

int instance variables


month day year public Date( int theMonth, int theDay, int theYear )

Constructor

Method

ToDateString(): returns the string representation of a Date. CheckDay() Class Employee: is composed of two references of type string and two references of class Date

Instance variables

firstName lastName birthDate hireDate

References to Date objects

Methods:

ToEmployeeString(): returns a string containing the name of the Employee and the string representations of the Employees birthDate and hireDate Class CompositionTest: runs the application with method Main Code:

Microsoft 30

Example
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // Date class definition encapsulates month, day and year. using System; // Date class definition public class Date { Constructor that receives the month, day and private into month; // 1-12 private into day; // 1-31 based on month year arguments. Arguments are validated; if private into year; // any year they are not valid, the corresponding member is // constructor confirms proper value for month; // call method Check Day to confirm proper // value for day public Date( into theMonth, into theDay, into theYear ) { // validate month if ( theMonth > 0 && theMonth <= 12 ) month = theMonth; else { month = 1; Console.WriteLine( "Month {0} invalid. Set to month 1.", theMonth ); }

set to a default value

29 30 31 32

year = theYear; day = Check Day( theDay );

// could validate year // validate day

31

Example(2)
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 // utility method confirms proper day value // based on month and year private into Check Day( into test Day ) { into[] daysPerMonth = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // check if day in range for month if ( test Day > 0 && test Day <= daysPerMonth[ month ] ) return test Day; // check for leap year if ( month == 2 && test Day == 29 && ( year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 ) ) ) return test Day; Console.WriteLine( "Day {0} invalid. Set to day 1.", test Day ); return 1; // leave object in consistent state

}
// return date string as month/day/year public string ToDateString() { return month + "/" + day + "/" + year; } } // end class Date

Validate that the given month can have a given day number
32

Example(3)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // Employee class definition encapsulates employee's first name, // last name, birth date and hire date. Two Date objects are members using System; // Employee class definition public class Employee { private string firstName; private string lastName; private Date birthDate; private Date hireDate; // constructor initializes name, birth date and hire date public Employee( string first, string last, int birthMonth, int birthDay, int birthYear, int hireMonth, int hireDay, int hireYear ) { firstName = first; lastName = last; // create new Date for Employee birth day birthDate = new Date( birthMonth, birthDay, birthYear ); hireDate = new Date( hireMonth, hireDay, hireYear ); }

of the Employee class

Constructor that initializes the employees Microsoft name, birth date and hire date

Example(4)
28 29 30 31 32 33 34 35 36 // convert Employee to String format public string ToEmployeeString() { return lastName + ", " + firstName + " Hired: " + hireDate.ToDateString() + " Birthday: " + birthDate.ToDateString(); } } // end class Employee

Microsoft

Example(5)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // Demonstrate an object with member object reference. using System; using System.Windows.Forms; // Composition class definition class CompositionTest { // main entry point for application static void Main( string[] args ) { Employee e = new Employee( "Bob", "Jones", 7, 24, 1949, 3, 12, 1988 ); MessageBox.Show( e.ToEmployeeString(), "Testing Class Employee" ); } // end method Main } // end class CompositionTest

Microsoft

Roadmap

3.9. Using the this Reference 3.10. Garbage Collection 3.11. static Class Members 3.12. const and readonly Members 3.13. Indexers 3.14. Data Abstaction and Information Hiding 3.15. Software Reusability 3.16. Namespace and Assemplies

Microsoft 36

3.9. Using the this Reference


C# supplies a this key word that provides access to the current class instance Uses of this keyword

Resolve scope ambiguity


chaining

Design a class using technique termed constructor

Arise when an incoming paramerter is named identically to a data field of the type

Example:

Helpful when declaring multiple constructors

Microsoft 37

Class Motorcycle
Instance

variables

driverIntensity Name SetDriverName(string)

Method

class Motorcycle { public int driverIntensity; public string name; public void SetDriverName(string name) { name = name; } ... }

public void SetDriverName(string name) { this.name = name; }

Problem: The impementation of SetDriverName() assigns the incoming parameter back to itself

Microsoft 38

Example
class Motorcycle { public int driverIntensity; Constructor public string driverName; chaining // Constructor chaining. public Motorcycle() {} public Motorcycle(int intensity): this(intensity, "") {} public Motorcycle(string name): this(0, name) {} // This is the 'master' constructor that does all the real work. public Motorcycle(int intensity, string name) { if (intensity > 10) { intensity = 10; } driverIntensity = intensity; driverName = name; } ... }

Roadmap

3.9. Using the this Reference 3.10. Garbage Collection 3.11. static Class Members 3.12. const and readonly Members 3.13. Indexers 3.14. Data Abstaction and Information Hiding 3.15. Software Reusability 3.16. Namespace and Assemplies

Microsoft 40

3.10. Garbage Collection


One of the key facilities in the CLR is the garbage collector GC frees you from the burden of handling memory allocation and deallocation The execution environment handles the tracking of object references and distroys the object instances when theyre no longer use Forcing a Garbage Collection: In some situations, it may be beneficial to programmatically force a garbage collection using GC.Collect()

Microsoft 41

static void Main(string[] args) { ... // Force a garbage collection and wait for // each object to be finalized. GC.Collect(); GC.WaitForPendingFinalizers(); ... }

Microsoft 42

Finalizer( Destructor)

Returns resources to the system Each class can contain only one destructor Name:

Is an override of a virtual method on System.Object Has no return type, no access modifiers Not inherited

Is formed by preceding the class name with a ~ charater

Microsoft 43

using System; public class Base { ~Base() { Console.WriteLine("Base.~Base()"); } } public class Derived : Base { ~Derived() { Console.WriteLine("Derived.~Derived()"); } } public class EntryPoint { static void Main() { Derived derived = new Derived(); } }

Destructor of Base class

Destructor of Derived class

Microsoft 44

Roadmap

3.9. Using the this Reference 3.10. Garbage Collection 3.11. static Class Members 3.12. const and readonly Members 3.13. Indexers 3.14. Data Abstaction and Information Hiding 3.15. Software Reusability 3.16. Namespace and Assemplies

Microsoft 45

3.11. static Class Members


A program contains only one copy of each of a classs static variables in memory A static variable represents class-wide information The declaration of a static member begins with the keyword static A static variable can be initialized in its declaration Static members:

static method static data static constructor static class

Microsoft 46

Example
using System; public static class StaticClass { public static void DoWork() { ++callCount; Console.WriteLine("StaticClass.DoWork()"); } public class NestedClass { public NestedClass() { Console.WriteLine("NestedClass.NestedClass()"); } } private static long callCount = 0; public static long CallCount { get { return callCount; } } } public static class EntryPoint { static void Main() { StaticClass.DoWork(); // OOPS! Cannot do this! // StaticClass obj = new StaticClass(); StaticClass.NestedClass nested = new StaticClass.NestedClass(); Console.WriteLine("CallCount = {0}", Can not StaticClass.CallCount); } }

static class is a collection of static members and can not have object instanced from

constants and nested types declared within a static class are static by default

do this

Roadmap

3.9. Using the this Reference 3.10. Garbage Collection 3.11. static Class Members 3.12. const and readonly Members 3.13. Indexers 3.14. Data Abstaction and Information Hiding 3.15. Software Reusability 3.16. Namespace and Assemplies

Microsoft 48

3.12.const and readonly Members


Constant Data Read-Only Field

Microsoft 49

constant Data

const syntax:

accessibility modifier const constname=initialization;

Are initialized at compile time using a constant expression and cannot be modified at run time
public class ZClass { public const int fielda = 5, fieldb = 15; // Error public static int fieldd=15; public const int fieldc = fieldd + 10; }

Microsoft 50

readonly Field

A read-only field cannot be changed after the initial assignment The value assigned to a read-only field can be determined at runtime
class MyMathClass { // Read-only fields can be assigned in ctors, // but nowhere else. public readonly double PI; public MyMathClass() { PI = 3.14; } } class MyMathClass { public readonly double PI; public MyMathClass() { PI = 3.14; } // Error! public void ChangePI() { PI = 3.14444; } }
Microsoft 51

Roadmap

3.9. Using the this Reference 3.10. Garbage Collection 3.11. static Class Members 3.12. const and readonly Members 3.13. Indexers 3.14. Data Abstaction and Information Hiding 3.15. Software Reusability 3.16. Namespace and Assemplies

Microsoft 52

3.13. Indexers

Allow to treat an object instance as if it were an array Are instance-based and work on a specific instance of an object of the defining class Cannot pass the results of calling an indexer on an object as an out or ref parameter to a method as with a real array this[] syntax

Microsoft 53

class Person { private string FirstName; private string LastName; private int Age; ... }
// Add the indexer to the existing class definition. public class PeopleCollection : IEnumerable { private ArrayList arPeople = new ArrayList(); // Custom indexer for this class. public Person this[int index] { get { return (Person)arPeople[index]; } set { arPeople.Insert(index, value); } } ... }
Indexer is created using this[] syntax

to get static void UseGenericListOfPeople() value { List<Person> myPeople = new List<Person>(); myPeople.Add(new Person("Lisa", "Simpson", 9)); myPeople.Add(new Person("Bart", "Simpson", 7)); // Change first person with indexer. myPeople[0] = new Person("Maggie", "Simpson", 2); // Now obtain and display each item using indexer. for (int i = 0; i < myPeople.Count; i++) { Console.WriteLine("Person number: {0}", i); Console.WriteLine("Name: {0} {1}", myPeople[i].FirstName, myPeople[i].LastName); Console.WriteLine("Age: {0}", myPeople[i].Age); Console.WriteLine(); } }

Using indexer

Microsoft 54

Overloaded Indexer Methods


public sealed class DataTableCollection : InternalDataCollectionBase { ... // Overloaded indexers! public DataTable this[string name] { get; } public DataTable this[string name, string tableNamespace] { get; } public DataTable this[int index] { get; } }

Microsoft 55

Example
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data;

Indexer declaration; indexer receives an integer to specify which dimension is wanted If the index requested is out o bounds, return 1; otherwis The get index accessor return the appropriate eleme

// Box class definition represents a box with length, // width and height dimensions public class Box { private string[] names = { "length", "width", "height" }; private double[] dimensions = new double[ 3 ]; // constructor public Box( double { dimensions[ 0 ] dimensions[ 1 ] dimensions[ 2 ] }

length, double width, double height ) = length; = width; = height;

// access dimensions by index number public double this[ int index ] { get { return ( index < 0 || index > dimensions.Length ) ? -1 : dimensions[ index ]; }

Example(2)
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 set { if ( index >= 0 && index < dimensions[ index ] = value; } } // end numeric indexer // access dimensions by their names public double this[ string name ] { get { // locate element to get int i = 0;

Indexer that takes the name of the dimension as an argument dimensions.Length )

The set accessor for the index Validate that the user wishes to set a valid index in the array and then set it

while ( i < names.Length && name.ToLower() != names[ i ] ) i++;

return ( i == names.Length ) ? -1 : dimensions[ i ]; } set { // locate element to set int i = 0; while ( i < names.Length && name.ToLower() != names[ i ] ) i++;

Example(3)
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 if ( i != names.Length ) dimensions[ i ] = value; } } // end indexer } // end class Box // Class IndexerTest public class IndexerTest : System.Windows.Forms.Form { private System.Windows.Forms.Label indexLabel; private System.Windows.Forms.Label nameLabel; private System.Windows.Forms.TextBox indexTextBox; private System.Windows.Forms.TextBox valueTextBox; private System.Windows.Forms.Button nameSetButton; private System.Windows.Forms.Button nameGetButton; private System.Windows.Forms.Button intSetButton; private System.Windows.Forms.Button intGetButton; private System.Windows.Forms.TextBox resultTextBox;

// required designer variable private System.ComponentModel.Container components = null;


private Box box; // constructor public IndexerTest() { // required for Windows Form Designer support InitializeComponent();

Example(4)
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 } // create block box = new Box( 0.0, 0.0, 0.0 );

Use the get accessor of the indexer Use the set accessor of the indexer

// Visual Studio .NET generated code // main entry point for application [STAThread] static void Main() { Application.Run( new IndexerTest() ); }

// display value at specified index number private void ShowValueAtIndex( string prefix, int index ) { resultTextBox.Text = prefix + "box[ " + index + " ] = " + box[ index ]; } // display value with specified name private void ShowValueAtIndex( string prefix, string name ) { resultTextBox.Text = prefix + "box[ " + name + " ] = " + box[ name ]; } // clear indexTextBox and valueTextBox private void ClearTextBoxes() { indexTextBox.Text = ""; valueTextBox.Text = ""; }

Example(5)
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 // get value at specified index private void intGetButton_Click( object sender, System.EventArgs e ) { Use ShowValueAtIndex( "get: ", Int32.Parse( indexTextBox.Text ) ); ClearTextBoxes(); }

integer indexer to set value

// set value at specified index private void intSetButton_Click( object sender, System.EventArgs e ) Use integer indexer to get value { int index = Int32.Parse( indexTextBox.Text ); Use string indexer to get value box[ index ] = Double.Parse( valueTextBox.Text );

ShowValueAtIndex( "set: ", index ); ClearTextBoxes();


} // get value with specified name private void nameGetButton_Click( object sender, System.EventArgs e ) { ShowValueAtIndex( "get: ", indexTextBox.Text ); ClearTextBoxes(); }

Example(6)
166 167 168 169 170 171 172 173 174 175 176 177 // set value with specified name private void nameSetButton_Click( object sender, System.EventArgs e ) { box[ indexTextBox.Text ] = Double.Parse( valueTextBox.Text ); ShowValueAtIndex( "set: ", indexTextBox.Text ); ClearTextBoxes(); } } // end class IndexerTest

Before setting value by index number

After setting value by index number

Microsoft

Example(8)

Before getting value by dimension name

After getting value by dimension name

Before setting value by dimension name

Microsoft

Example(9)

After setting value by dimension name

Before getting value by index number

After getting value by index number

Microsoft

Roadmap

3.9. Using the this Reference 3.10. Garbage Collection 3.11. static Class Members 3.12. const and readonly Members 3.13. Indexers 3.14. Data Abstaction and Information Hiding 3.15. Software Reusability 3.16. Namespace and Assemplies

Microsoft 64

3.14. Data Abstraction and Information Hiding

Classes normally hide the details of their implementation from their clients Data Abstraction: Information hiding

Example: stack, queue

Abstract Data Type (ADT): the programming-languages


community needed to formalize some notions about data Data representation Operation Example: int is an abstract representation of an integer

Microsoft 65

Roadmap

3.9. Using the this Reference 3.10. Garbage Collection 3.11. static Class Members 3.12. const and readonly Members 3.13. Indexers 3.14. Data Abstaction and Information Hiding 3.15. Software Reusability 3.16. Namespace and Assemplies

Microsoft 66

3.15. Software Reusability

Framework Class Library (FCL):

Contain thousands of predefined classes

Allow to achieve software reusability across platforms that support


Enable C# developers to build applications faster by reusing preexisting, extensively tested classes Include classes for creating Web services

Microsoft 67

Roadmap

3.9. Using the this Reference 3.10. Garbage Collection 3.11. static Class Members 3.12. const and readonly Members 3.13. Indexers 3.14. Data Abstaction and Information Hiding 3.15. Software Reusability 3.16. Namespace and Assemplies

Microsoft 68

3.16. Namespaces and Assembly


Namespace helps to solve naming collision problems Reusing class definitions between programs

public class can be reused from class libraries Non-public classes can be used only by other classed in the same assemply

A dynamic link library represents an assembly When a project uses a class library, it must contain a reference to the assembly that defines the class library

Microsoft 69

3.16. Namespaces and Assembly(2)

Orthogonal concepts:

namespace for organization assembly for packaging

One namespace could be spread across multiple assemblies One assembly may contain multiple namesspaces

e.g. mscorlib.dll

Microsoft 70

Summary

Youve learned the basic knowledge of object-oriented programming in C#, including the use of classes and their members. Youve also informed about garbage collection in C#, how to use information hiding as well as data abstraction in C#

Microsoft 71

Das könnte Ihnen auch gefallen