10266A_06.ppt
- Количество слайдов: 26
Module 6 Creating New Types
Module Overview • Creating and Using Enumerations • Creating and Using Classes • Creating and Using Structures • Comparing References to Values
Lesson 1: Creating and Using Enumerations • What Are Enumerations? • Creating New Enum Types • Initializing and Assigning Enum Variables
What Are Enumerations? An enumeration type specifies a set of named constants Days Monday Tuesday Wednesday. . . Benefits include: Code is easier to maintain because you assign only expected values to your variables Code is easier to read because you assign easily identifiable names to your values Code is easier to write because Intelli. Sense displays a list of the possible values that you can use
Creating New Enum Types Define enumerations with the enum keyword enum Name : Data. Type { Value 1, Value 2. . . }; You can define enumerations in namespaces and classes but not in methods Enumerations values start at 0 by default, unless explicitly stated namespace Fabrikam. Custom. Enumerations { enum Days : int { Monday = 1, Tuesday = 2, Wednesday = 3 }; . . . }
Initializing and Assigning Enum Variables Instantiate enumeration variables in the same way as any other type [Enum. Type] variable. Name = [Enum. Value] You can only assign an enumeration a value defined in its definition enum Days : int { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7 }; static void Main(string[] args) { Days my. Day. Off = Days. Sunday; Assign value Sunday } You can perform simple operations on an enumeration for (Days day. Of. Week = Days. Monday; day. Of. Week <= Days. Sunday; day. Of. Week++) {. . . }
Lesson 2: Creating and Using Classes • What Is a Class? • Adding Members to Classes • Defining Constructors and Initializing an Object • Creating Objects • Accessing Class Members • Using Partial Classes and Partial Methods
What Is a Class? A class is a blueprint from which you can create objects A class defines the characteristics of an object Class definition with class keyword class House {. . . } An object is an instance of a class my. House your. House
Adding Members to Classes Members define the data and behavior of the class public class Property { public Property. Type type; public int number. Of. Bedrooms; Fields public bool has. Garage; public bool has. Garden; public int Calculate. Sale. Price() { // Code to calculate the sale value of // the property. } public int Calculate. Rebuilding. Cost() { // Code to calculate the rebuilding costs // of the property. } } Methods
Defining Constructors and Initializing an Object A constructor is a special method that the runtime invokes implicitly public class Property { public Property(Property. Type type, int number. Of. Bedrooms) { } public Property(Property. Type type, int number. Of. Bedrooms, bool has. Garage, bool has. Garden) { } } Three constructors If you do not initialize a field in a class, it is assigned its default value
Creating Objects Object are initially unassigned Before you can use a class, you must create an instance of that class You can create a new instance of a class by using the new operator The new operator does two things: • Causes the CLR to allocate memory for the object • Invokes a constructor to initialize the object // Create a Flat with 2 bedrooms. Property my. Flat = new Property(Property. Type. Flat, 2); // Create a House with 3 bedrooms and a garage Property my. House = new Property(Property. Type. House, 3, true); // Create a Bungalow with 2 bedrooms, a garage, and a garden Property my. Bungalow = new Property(Property. Type. Bungalow, 2, true);
Accessing Class Members Access object members by using the instance name followed by a period Instance. Name. Member. Name Example // Create a 3 bedroom house. Property my. House = new Property(Property. Type. House, 3); // Indicate that the property has a garden. my. House. has. Garden = true; // Calculate the market value. int sale. Price = my. House. Calculate. Sale. Price(); // Get the rebuilding costs. int rebuild. Cost = my. House. Calculate. Rebuilding. Cost();
Using Partial Classes and Partial Methods Split a class definition across multiple source files Prefix the class and method declarations with the partial keyword public partial class Property { partial void Sale. Property(string name); } Definition of Sale. Property method public partial class Property { partial void Sale. Property(string name) { //Logic goes here. } } Implementation of Sale. Property method All parts of the partial class and method must be available during compilation Compiled into a single entity
Lesson 3: Creating and Using Structures • What Are Structures? • Defining and Using a Structure • Initializing a Structure
What Are Structures? All structures are value types System. Byte System. Int 16 System. Int 32 System. Int 64 System. Single System. Double System. Decimal System. Boolean System. Char The data in structures is stored on the stack Use structures to model items that contain small amounts of data Structures can contain fields and methods just like a class int x = 99; string x. As. String = x. To. String();
Defining and Using a Structure Use the struct keyword to declare a structure Define members in a structure in the same manner as a class struct Currency { public string currency. Code; public string currency. Symbol; public int fraction. Digits } Structures are automatically allocated memory on the stack Currency united. States. Currency; united. States. Currency. currency. Code = "USD"; united. States. Currency. currency. Symbol = "$"; united. States. Currency. fraction. Digits = 2; You do not have to use the new operator when you create an instance of a structure
Initializing a Structure The new operator only initializes fields in the structure struct Currency { public string currency. Code; public string currency. Symbol; public int fraction. Digits public Currency(string code, string symbol) { this. currency. Code = code; this. currency. Symbol = symbol; this. fraction. Digits = 2; } }; . . . Currency united. Kindgdom. Currency = new Currency("GBP", "£"); Always use a constructor to guarantee that the structure and fields are initialized
Lesson 4: Comparing References to Values • Comparing Reference Types to Value Types • Passing a Value Type by Reference into a Method • Boxing and Unboxing • Nullable Types
Comparing Reference Types to Value Types Reference types (reference on stack, value on heap) When you assign a reference, you simply refer to an object in memory If you assign the same reference to two different variables, both variables refer to the same object If you change the data in the object, the changes will be reflected in all variables that reference that object Value types (value on stack) When you copy a value type, the variables do not refer to the same object If you change the data in either variable, the changes will not be reflected in other copies
Passing a Value Type by Reference into a Method static void Main(string[] args) { int my. Int = 1005; Change. Input(my. Int); } my. Int still equals 1005 static void Change. Input(int input) { input = 29910; } static void Main(string[] args) { int my. Int = 1005; Change. Input(ref my. Int); } static void Change. Input(ref int input) { input = 29910; } my. Int now equals 29910
Boxing and Unboxing Boxing (value type to reference type) 1. The CLR allocates a piece of memory on the heap 2. The CLR copies the value from the stack to the new piece of memory Currency my. Currency = new Currency(); // Value type object o = my. Currency; // Box the value type into a reference Unboxing (reference type to value type) 1. The CLR checks the type of the boxed variable 2. If the types match, the CLR copies the value from the heap Currency my. Currency = new Currency(. . . ); object o = my. Currency; // boxing. . . Currency another. Currency = (Currency)o; // compiles okay
Nullable Types You can set a reference variable to null to indicate that it has not been initialized The null value is itself a reference, and there is no corresponding value for value types to indicate that they are uninitialized Currency my. Currency = null; // illegal You use a question mark (? ) to indicate that a value type is nullable Currency? my. Currency = null; // legal if (my. Currency == null) { } Nullable types expose the Has. Value and Value properties Currency? my. Currency = null; if (my. Currency. Has. Value) { Console. Write. Line(my. Currency. Value); }
Lab: Creating New Types • Exercise 1: Using Enumerations to Specify Domains • Exercise 2: Using a Struct to Model a Simple Type • Exercise 3: Using a Class to Model a More Complex Type • Exercise 4: Using a Nullable Struct Logon information Virtual machine 10266 A-GEN-DEV User name Student Password Pa$$w 0 rd Estimated time: 60 minutes
Lab Scenario
Lab Review Questions • What type would you use to model a collection of constant values? • At what scope level would you define an enumeration type, if you wanted that type to be accessible to multiple classes? • What construct would you use to model a simple custom numeric type?
Module Review and Takeaways • Review Questions • Best Practices