Chapter 14 C# - 2008 Language Features pot

67 194 0
Chapter 14 C# - 2008 Language Features pot

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 14 C# 2008 Language Features Hoang Anh Viet VietHA@it-hut.edu.vn Hanoi University of Technology Objectives “With the release of NET 3.5, the C# language has been enhanced to support a great number of new programming constructs, many of which are used to enable the LINQ API (which you will begin to examine in Chapter 15) Here, you will learn the role of implicit typing of local variables, partial methods, automatic properties, extension methods, anonymous types, and object initialization syntax.” Microsoft Roadmap 14.1 Understanding Implicitly Typed Local Variables 14.2 Understanding Automatic Properties 14.3 Understanding Extension Methods 14.4 Understanding Partial Methods 14.5 Understanding Object Initializer Syntax 14.6 Understanding Anonymous Types Microsoft 14.1 Understanding Implicitly Typed Local Variables  C# 2008 now provides a new keyword, var, which you can use in place of specifying a formal data type (such as int, bool, or string) The compiler will automatically infer the underlying data type based on the initial value used to initialize the local data point static void DeclareImplicitVars() { // Implicitly typed local variables // are declared as follows: // var variableName = initialValue; var myInt = 0; var myBool = true; var myString = "Time, marches on "; } Microsoft Implicitly Typed Local Variables  In this case, the compiler is able to infer that myInt is in fact a System.Int32, myBool is a System.Boolean, and myString is indeed of type System.String, given the initially assigned value Microsoft Implicitly Typed Local Variables  You can use this implicit typing for any type including arrays, generic types, and your own custom types Microsoft Use of var Within foreach Constructs  Use of implicit typing within a foreach looping construct static void VarInForeachLoop() { var evenNumbers = new int[] { 2, 4, 6, }; // Use "var" in a standard foreach loop foreach (var item in evenNumbers) { Console.WriteLine("Item value: {0}", item); } } Microsoft Use of var Within foreach Constructs  A foreach loop can make use of a strongly typed iterator when processing an implicitly defined local array Microsoft Restrictions on Implicitly Typed Variables  Implicit typing applies only to local variables in a method or property scope Microsoft Restrictions on Implicitly Typed Variables  Local variables declared with the var keyword must be assigned an initial value at the exact time of declaration and cannot be assigned the initial value of null Microsoft 10 Uses of Partial Methods  In C# 2008, partial methods will more likely than not be the least used among them   By marking this method with the partial modifier, other class builders have the option of providing implementation details if they so choose   In the current example, the VerifyDuplicates() method was marked as partial for illustrative purposes; however, imagine that this method, if implemented, had to perform some very intensive calculations In this case, partial methods provide a cleaner solution than using preprocessor directives, supplying “dummy” implementations to virtual methods or throwing NotImplementedException objects The most common use of this syntax is to define what are termed lightweight events Microsoft 53 Roadmap 14.1 Understanding Implicitly Typed Local Variables 14.2 Understanding Automatic Properties 14.3 Understanding Extension Methods 14.4 Understanding Partial Methods 14.5 Understanding Object Initializer Syntax 14.6 Understanding Anonymous Types Microsoft 54 14.5 Understanding Object Initializer Syntax   A new way to hydrate the state of a new class or structure variable An object initializer consists of a comma-delimited list of specified values, enclosed by the { and } tokens static void Main(string[] args) { // Make a Point by setting each property manually Point firstPoint = new Point(); firstPoint.X = 10; firstPoint.Y = 10; // or make a Point via a custom constructor Point anotherPoint = new Point(20, 20); // or make some Point types using the new object init syntax var yetAnotherPoint = new Point { X = 30, Y = 30 }; Point finalPoint = new Point { X = 30, Y = 30 }; } Microsoft 55 Calling Custom Constructors with Initialization Syntax  The previous examples initialized Point types by implicitly calling the default constructor on the type  If you wish to be very clear about this, it is permissible to explicitly call the default constructor as follows Microsoft 56 Calling Custom Constructors with Initialization Syntax  Therefore, the following Point declaration results in an X value of 100 and a Y value of 100, regardless of the fact that our constructor arguments specified the values 10 and 16  Given the current definition of our Point type, calling the custom constructor while using initialization syntax is not terribly useful (and more than a bit verbose) Microsoft 57 Example 14.5 Calling Custom Constructors with Initialization Syntax 58 Roadmap 14.1 Understanding Implicitly Typed Local Variables 14.2 Understanding Automatic Properties 14.3 Understanding Extension Methods 14.4 Understanding Partial Methods 14.5 Understanding Object Initializer Syntax 14.6 Understanding Anonymous Types Microsoft 59 14.6 Understanding Anonymous Types  Problem:   While building such a class is not rocket science, it can be rather labor intensive if you are attempting to encapsulate more than a handful of members As of C# 2008, we are now provided with a massive shortcut for this very situation termed anonymous types, which in many ways is a natural extension of C#’s anonymous methods syntax Microsoft 60 Anonymous Types   Create a new Console Application named AnonymousTypes Now, update Main() with the following anonymous class, which models a simple car type Microsoft 61 Anonymous Types    Again note that the myCar variable must be implicitly typed, which makes good sense, as we are not modeling the concept of an automobile using a strongly typed class definition At compile time, the C# compiler will autogenerate a uniquely named class on our behalf Given the fact that this class name is not visible from C#, the use of implicit typing using the var keyword is mandatory Also notice that we have to specify (using object initialization syntax) the set of properties that model the data we are attempting to encapsulate Once defined, these values can then be obtained using standard C# property invocation syntax Microsoft 62 The Internal Representation of Anonymous Types  All anonymous types are automatically derived from System.Object, and therefore support each of the members provided by this base class Assume our Program class defines the following static helper function Microsoft 63 The Internal Representation of Anonymous Types  Invoke this method from Main(), passing in the myCar object as the parameter Microsoft 64 Anonymous Types Containing Anonymous Types   It is possible to create an anonymous type that is composed of additional anonymous types For example, assume you wish to model a purchase order that consists of a timestamp, a price point, and the automobile purchased Microsoft 65 Summary    C# 2008 provides a number of very interesting features that bring C# into the family of functional languages Described the role of automatic properties, partial methods, extension methods (which allow you to add new functionality to a compiled type), and the syntax of object initialization (which can be used to assign property values at the time of construction) Wrapped up by examining the use of anonymous types Microsoft 66 References  Books:  Microsoft Andrew Troelsen, “Pro C# 2008 and the NET 3.5 Platform” 67 ... Microsoft Roadmap 14. 1 Understanding Implicitly Typed Local Variables 14. 2 Understanding Automatic Properties 14. 3 Understanding Extension Methods 14. 4 Understanding Partial Methods 14. 5 Understanding... Microsoft 15 Roadmap 14. 1 Understanding Implicitly Typed Local Variables 14. 2 Understanding Automatic Properties 14. 3 Understanding Extension Methods 14. 4 Understanding Partial Methods 14. 5 Understanding... Automatic Properties 14. 3 Understanding Extension Methods 14. 4 Understanding Partial Methods 14. 5 Understanding Object Initializer Syntax 14. 6 Understanding Anonymous Types Microsoft 28 14. 3 Understanding

Ngày đăng: 02/08/2014, 09:20

Mục lục

    14.1 Understanding Implicitly Typed Local Variables

    Implicitly Typed Local Variables

    Use of var Within foreach Constructs

    Restrictions on Implicitly Typed Variables

    Implicitly Typed Local Arrays

    Implicit Typed Data Is Strongly Typed Data

    Usefulness of Implicitly Typed Local Variables

    Interacting with Automatic Properties

    Restricting Access on Automatic Properties

    Regarding Automatic Properties and Default Values

Tài liệu cùng người dùng

Tài liệu liên quan