C # Advanced Programming Seventh Edition learning Notes chapter III Objects and types

Source: Internet
Author: User

Chapter III Objects and types

The contents of this chapter:

The difference between class and structure

Class Member

Passing parameters by value and by reference

Method overloading

Constructors and Static constructors

Read-only fields

Partial classes

Static class

Object class, and other types derive from this class

3.1 Classes and structures

Classes and structs are templates that create objects, each of which contains data and provides methods for processing and accessing the data

The difference between structs and classes is how they are stored in memory, how they are accessed (classes are reference types stored on the heap, and structures are value types stored on the stack) and some of their characteristics (such as structs do not support inheritance). Using structs for smaller data types can improve performance. But syntactically, structs and classes are very similar, and the main difference is that they use the keyword struct instead of class to declare the structure.

For classes and institutions, use the keyword new to declare an instance.

Class 3.2

3.2.1 Data members

The data and functions in the class are called members of the class. Data members and function members

Accessibility of Members: public, protected, internal protected, private, or internal

Data members: Fields, constants, and events

Use the CONST keyword to declare constants.

Function members provide some functionality for manipulating data in classes, including methods, properties, constructors, and finalizers (finalizer), operators, and their indexers

3.2.2 Function members

A constructor is a special function that is called automatically when an object is instantiated. They must have the same name as the owning one and cannot have a return type. constructor is used to initialize the value of the field

A finalizer is similar to a constructor, but it is called when the CLR detects that an object is no longer needed. They have the same name as the class, but preceded by a "~" symbol

Indexers allow an object to be indexed as an array or as a collection

If a parameter is passed to the method and the input parameter of the method is preceded by the REF keyword, any changes made to the variable by the method will affect the value of the original object

C # requires that parameters passed to a method be initialized, and any variables must be initialized before being passed to a method, whether by value or by reference.

Variables with the Out keyword can be used without initialization

Parameters can also be optional, and default values must be provided for optional parameters. The optional parameter must also be the last parameter of the method definition.

The overloads of the C # support method-----Several versions of the method have different signatures (that is, the method name is the same, but the number of parameters and/or the type differs). To overload a method, simply declare a method with the same name but with a different parameter or type.

A new feature of C # is that you can also write a parameterless static constructor to a class. This constructor runs only once, and the preceding constructor is an instance constructor that executes as soon as the object of the class is created.

One reason for writing a static constructor is that the class has some static fields or properties that need to be initialized from an external source before the class is first used.

The static constructor does not have an access modifier, and other C # code never calls it, but when the class is loaded, it is always made by. NET runtime, it makes no sense to access modifiers like public or private. For the same reason, a static constructor cannot have any arguments, and a class can have only one static constructor. It is clear that static constructors can only access static members of a class and cannot access instance members of the class.

Note that parameterless instance constructors and static constructors can be defined at the same time in the same class. Although the parameter list is the same, this is not contradictory because the static constructor is executed when the class is loaded, and the instance constructor is executed when the instance is created, so there is no conflict when to execute which constructor.

public class Userpreference

{

public static readonly Color BackColor;

Static Userpreference ()

{

DateTime now = DateTime.Now;

if (now. DayOfWeek = = Dayofweek.saturday)

{

BackColor = Color.green;

}

Else

{

BackColor = color.red;

}

}

}

Calling other constructors from a constructor

Class Car

{

private string description;

orivate UINT Nwheels;

Public Car (string description, uint nwheels)

{

this.description = description;

This.nwheels = Nwheels;

}

Public Car (String description): this (description,4)

{}

}

3.2.3 Read-only fields

A read-only field can only be assigned to it in a constructor and cannot be assigned anywhere else. A read-only field can also be an instance field, not a static field, and each instance of a class can have a different value. Unlike the const field, if you want to set a read-only field to static, you must display the declaration of it

3.3 Anonymous Types

An anonymous type is simply a class that inherits from object and has no name.

var captain = new {person. FirstName, person. MiddleName, person. LastName};

3.4 Structure

A struct is a value type, not a reference type. They are stored on the stack or stored as inline (inline) (if they are part of another object stored in the heap), with a lifetime limit of the same as a simple data type.

Structure does not support inheritance

There are some differences in how a struct constructor works. In particular, the compiler always provides a default constructor with no parameters, and he is not allowed to replace it.

Use structs to specify how fields are laid out in memory

3.4.1 structure is a value type

Although structs are value types, they can often be treated as classes on a single syntax.

Note: Because structs are value types, the new operator works in a different way than other reference types. The new operator does not allocate memory in the heap, but instead invokes only the corresponding constructor, initializing all fields according to the parameters passed to him. For structures. A variable declaration is actually allocating space in the stack for the entire structure.

Structs follow the rules that other data types follow: All elements must be initialized before they are used. The structure is fully initialized by using the new operator on the structure, or assigning values to all the fields individually.

3.4.2 Structure and inheritance

A struct is not designed for inheritance, which means that it cannot inherit from a struct.

Constructors for 3.4.3 Structures

You define constructors for structs in the same way that you define constructors for a class, but you are not allowed to define parameterless constructors.

3.5 Parts Category

The partial keyword runs to put a class, struct, or interface in multiple files.

3.6 Static Classes

3.7 Object

All of them. NET classes are derived from System.Object. In fact, if you do not specify a base class when you define a class, the compiler automatically assumes that the class derives from object. Structs are always derived from System.valuetype,system.valuetype and derived from System.Object

The practical implication is that, in addition to the methods and properties that you define, you can access many public and protected member methods that are defined for object. These methods can be used in all other classes that you define.

3.7.1 System.Object () method

3.7.2 ToString () method

If you do not override ToString () in a self-defined class, the class inherits only the System.Object implementation. He displays the name of the class.

3.8 Extension methods

An extension method is a static method, which is part of a class, but is not actually placed in the source code of the class. Suppose that the money class needs a method Addtoamount (decimal amounttoadd). However, for some reason, the original source code of the program can not be directly modified, all that must be done is to create a static class, the method Addtoamount () Added as a static method. The corresponding code is as follows:

Namespace Wrox

{

public static Class Moneyextension

{

public static void Addtoamoumt (this money money,decimal amounttoadd)

{

Money. Amount + = Amounttoadd;

}

}

}

Note the parameters of the Addtoamount () method, for extension methods, the first parameter is the type to extend, which is placed after the This keyword. This tells the compiler that this method is part of the money type. In an extension method, you can access all public methods and properties of the extended type.

3.9 Summary

C # Advanced Programming Seventh Edition learning Notes chapter III Objects and types

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.