Скачать презентацию Module 10 Encapsulating Data and Defining Overloaded Operators Скачать презентацию Module 10 Encapsulating Data and Defining Overloaded Operators

10266A_10.ppt

  • Количество слайдов: 33

Module 10 Encapsulating Data and Defining Overloaded Operators Module 10 Encapsulating Data and Defining Overloaded Operators

Module Overview • Creating and Using Properties • Creating and Using Indexers • Overloading Module Overview • Creating and Using Properties • Creating and Using Indexers • Overloading Operators

Lesson 1: Creating and Using Properties • What Is a Property? • Defining a Lesson 1: Creating and Using Properties • What Is a Property? • Defining a Property • Automatic Properties • Instantiating an Object by Using Properties • Defining Properties in an Interface • Best Practices When Using Properties • Demonstration : Using Properties

What Is a Property? Method-like behavior Field-like syntax Property: get and set accessors Properties What Is a Property? Method-like behavior Field-like syntax Property: get and set accessors Properties can provide: • Controlled access to data • Validation • Read/write control

Defining a Property Specify the access modifier Optionally specify an access modifier for the Defining a Property Specify the access modifier Optionally specify an access modifier for the get or set accessor Specify the property type name private string my. String; public string My. String { get { return my. String; } private set { my. String = value; } } Add get and/or set accessors Use the value keyword in the set accessor to access the data passed to the property

Automatic Properties public string Name { get; set; } The automatic property shown above Automatic Properties public string Name { get; set; } The automatic property shown above it converted by the compiler to code similar to: private string _name; public string Name { get { return _name; } set { this. _name = value; } } • Useful when you do not need to add custom logic to the property accessors • Must specify both get and set accessors • Important forward compatibility • No difference between automatic properties and normal properties to consuming applications

Instantiating an Object by Using Properties Employee john = new Employee { Name = Instantiating an Object by Using Properties Employee john = new Employee { Name = "John" }; Employee louisa = new Employee() { Department = "Technical" }; Employee mike = new Employee { Name = "Mike", Department = "Technical" }; • An object initializer avoids problems with defining several constructors • A default constructor should instantiate properties to default values • A constructor is called the object initializer • A constructor is always run first, properties are set after so properties take precedence • An object initializer can use no brackets to call the default constructor, brackets with no parameters to explicitly call the default constructor, or brackets with parameters to call a nondefault constructor

Defining Properties in an Interface An interface is a contract between a type and Defining Properties in an Interface An interface is a contract between a type and a consuming application It does not contain implementation details Fields are considered implementation details; they cannot be defined in an interface Properties are not implementation details; they are data exposed for consumption so they can be defined in an interface Do not specify an interface IPerson { string Name { get; set; } int Age { get; } Date. Time Date. Of. Birth { set; } } Syntax the same as an automatic property; except you access do not have to specify modifier both accessors

Best Practices When Using Properties Only expose properties where they are appropriate! Bank. Account Best Practices When Using Properties Only expose properties where they are appropriate! Bank. Account double Balance (get, set) ü Withdraw. Money(double Amount) ü Deposit. Money (double Amount) Would you let an application directly set a bank balance! Don’t add code to a get accessor that has any side effects on data Be careful to avoid accidentally recursive properties

Demonstration: Using Properties In this demonstration, you will: • Encapsulate data in a class Demonstration: Using Properties In this demonstration, you will: • Encapsulate data in a class by using properties • Add logic to the properties to prevent invalid data

Lab A: Creating and Using Properties • Exercise 1: Defining Properties in an Interface Lab A: Creating and Using Properties • Exercise 1: Defining Properties in an Interface • Exercise 2: Implementing Properties in a Class • Exercise 3: Using Properties Exposed by a Class Logon information Virtual machine 10266 A-GEN-DEV User name Student Password Pa$$w 0 rd Estimated time: 25 minutes

Lab Scenario Lab Scenario

Lab Review • What is the syntax for declaring a property in an interface? Lab Review • What is the syntax for declaring a property in an interface? • What is the significant difference between automatic properties and nonautomatic properties? • What happens if you attempt to write to a property that exposes only a get accessor?

Lesson 2: Creating and Using Indexers • What Is an Indexer? • Creating an Lesson 2: Creating and Using Indexers • What Is an Indexer? • Creating an Indexer • Comparing Indexers and Arrays • Defining an Indexer in an Interface • Demonstration: Creating and Using an Indexer

What Is an Indexer? • Provides array-like syntax for accessing members in a set What Is an Indexer? • Provides array-like syntax for accessing members in a set • Can use different subscripts to an array, for example, a string instead of an int • Can be overloaded Customer. Address. Book address. Book =. . . ; Address customer. Address = address. Book["a 2332"]; . . . customer. Address = address. Book[99];

Creating an Indexer The operator Specify the return Specify the parameters for should be Creating an Indexer The operator Specify the return Specify the parameters for should be public type the indexer public Customer this[string Customer. ID] { get { return database. Find. Customer(Customer. ID); } set { database. Update. Customer(Customer. ID, value); } } Use this keyword; all Add get and/or set accessors indexers must be called this to the indexer

Comparing Indexers and Arrays Subscripts Overloading Indexers Must use a numeric subscript to access Comparing Indexers and Arrays Subscripts Overloading Indexers Must use a numeric subscript to access individual members Can use nonnumeric subscripts, for example, strings to access individual members Cannot be overloaded in child classes Can be used as a normal parameter Method Parameters and a ref or out parameter Can only be used as a normal parameter; cannot be used as a ref or out parameter

Defining an Indexer in an Interface Indexers expose data to consuming classes; they are Defining an Indexer in an Interface Indexers expose data to consuming classes; they are not considered implementation details. Therefore indexers can be added to an interface Do not interface IEmployee. Database { Employee this[string Name] { get; set; } } specify an access modifier As with a property, you do not have to specify both accessors Like all members of an interface, you can choose to implement indexers implicitly or explicitly

Demonstration: Creating and Using an Indexer In this demonstration, you will: • Add an Demonstration: Creating and Using an Indexer In this demonstration, you will: • Add an indexer to a class • Use the indexer to access individual items in an array by specifying a name instead of an index

Lab B: Creating and Using Indexers • Exercise 1: Implementing an Indexer to Access Lab B: Creating and Using Indexers • Exercise 1: Implementing an Indexer to Access Bits in a Control Register • Exercise 2: Using an Indexer Exposed by a Class Logon information Virtual machine 10266 A-GEN-DEV User name Student Password Pa$$w 0 rd Estimated time: 25 minutes

Lab Scenario Lab Scenario

Lab Review • Can you overload an indexer in a child class? • What Lab Review • Can you overload an indexer in a child class? • What are some of the advantages of using an indexer in your class? • When can it be inappropriate to use an indexer in your class?

Lesson 3: Overloading Operators • What Is Operator Overloading? • Overloading an Operator • Lesson 3: Overloading Operators • What Is Operator Overloading? • Overloading an Operator • Restrictions When Overloading Operators • Best Practices When Overloading Operators • Implementing and Using Conversion Operators • Demonstration: Overloading an Operator

What Is Operator Overloading? - + / != Class My. Type {. . . What Is Operator Overloading? - + / != Class My. Type {. . . }. . . My. Type var 1 =. . . ; My. Type var 2 =. . . ; . . . ? = var 1 + var 2; ==

Overloading an Operator The operator Use the operator should be public must be static Overloading an Operator The operator Use the operator should be public must be static keyword public static Hour operator +(Hour lhs, Hour rhs) { return new Hour(lhs. value + rhs. value); } Specify a return Specify which operator Specify the operands type you are overloading for the operator

Restrictions When Overloading Operators 1 • You cannot change the precedence or associativity of Restrictions When Overloading Operators 1 • You cannot change the precedence or associativity of an operator 2 • You cannot change the multiplicity of an operator 3 • You cannot invent new operators (use methods instead) 4 • You cannot change the meaning of operators for built-in types 5 • You cannot overload all operators, for example, the dot (. ) operator 6 • You must define some operators in pairs (==, !=, etc)

Best Practices When Overloading Operators Define symmetric operators Do not modify operands ü ü Best Practices When Overloading Operators Define symmetric operators Do not modify operands ü ü public static Salary operator +(Salary salary, double number) { return new Salary(salary. amount + number); } public static Salary operator +(double number, Salary salary) { return salary + number; } Only define meaningful operators public static Bank. Account operator +(Bank. Account account, decimal amount) {. . . } public static Bank. Account operator -(Bank. Account account, decimal amount) {. . . }

Implementing and Using Conversion Operators Implicit conversion: No risk of data loss or exceptions Implementing and Using Conversion Operators Implicit conversion: No risk of data loss or exceptions Explicit conversion: Risk of data loss; requires a cast public static implicit operator int (Hour from) { return from. value; } public static void My. Method(int parameter) {. . . } public static void Main() { Hour lunch = new Hour(12); Example. My. Method(lunch); // implicit conversion } public static explicit operator Hour (int from) { return from. value; } public static void My. Other. Method(Hour parameter) {. . . } public static void Main() { int lunch = 12; Example. My. Other. Method((Hour)lunch); // explicit conversion }

Demonstration: Overloading an Operator In this demonstration, you will: • Overload the + operator Demonstration: Overloading an Operator In this demonstration, you will: • Overload the + operator in a class • Implement logic to add objects to an array by using the + operator

Lab C: Overloading Operators • Exercise 1: Defining the Matrix and Matrix. Not. Compatible. Lab C: Overloading Operators • Exercise 1: Defining the Matrix and Matrix. Not. Compatible. Exception Types • Exercise 2: Implementing Operators for the Matrix Type • Exercise 3: Testing the Operators for the Matrix Type Logon information Virtual machine 10266 A-GEN-DEV User name Student Password Pa$$w 0 rd Estimated time: 40 minutes

Lab Scenario Lab Scenario

Lab Review • Can you declare an operator that is not static? • Can Lab Review • Can you declare an operator that is not static? • Can you change the multiplicity of an operator? • What must a binary operator do to support compound assignment statements?

Module Review and Takeaways • Review Questions • Best Practices Module Review and Takeaways • Review Questions • Best Practices