2017-9-23c# Notes (index, event, operator, this accessor, derivation, partial class, abstract class, enclosing class, Static class, class and struct differ)

Source: Internet
Author: User
Tags modifiers

1. Index of Class

An index is a set of get and set front accessors that support referencing an object as a method of consuming an array element. An index is usually a number of data members, and it always exists as a case member of a Lei class. Method for declaring an index:

return type this [parameter list]



{    }


{        }


Example: Using System;

Using System.Collections.Generic;

Using System.Linq;

Using System.Text;

Namespace ConsoleApplication1//Introducing namespaces


Class Program


Class myclass{

int x;

int y;

public int This[int Index]//Declaration Index




if (index = = 0)

return x;


return y;




if (index = = 0)

x = value;


y = value;




static void Main (string[] args)


Myclass mc = new Myclass ();

Mc[0] = 10; Use the index to access the private field x;

MC[1] = 15; Use the index to access the private field y;

Console.WriteLine ("{0},{1}", Mc[0], mc[1]); Output 10, 15;

Console.read ();




2 . Events

An event is a member that can provide notification to an object or class. The client can add executable code for the corresponding event by providing an event handler. An event mechanism is a message that is not based on a specific operation that occurs when a will act message is received by an object that is concerned about the event, and the specified process begins. That is, the way the message is transmitted at the time of the event, the various instructions are passed through the message. The object that produces the event is called the event, or the recipient of the world.

3 . Operator

(1) Definition of operator

The operator can be used for the operator meaning of the class instance, as defined in the following form:

operator modifier type operate operation symbol (parameter list)


Statement sequence}

C # can be overloaded with operators:

①: unary operator: +,-,!, ~,++,--, true,false

②: Two-dollar operator: +,-, *,/,%,&,|,^,<<,>>

③: conversion operator: IMPLICIT,EXPLICIT;

The following rules apply to all operator declarations:

① operator declaration must contain both public and static modifiers

The parameter of the ② operator must be a holding parameter, specifying other shapes in the operator declaration to cause compile-time errors

The signature analogy of the ③ operator differs from the signature of all other operators declared in the same class

All types referenced in the ④ operator declaration must have the same accessibility as the operator's province

⑤ the same modifier in an operation declares multiple occurrences of the error;

4.this Accessors

The This keyword is a reference to the current object, and this access can only be used in instance constructors, instance methods, or access to instances of properties and indexes, and can no longer be used in code of any static function member. It is typically used for a two-point purpose:

①: Local variable parameters for members and methods of a zone classification

②: Used as a calling method parameter

5. Derivation

(1) Inheritance, encapsulation and polymorphism are the three main features of object-oriented programming

(2) All classes in C # inherit from the object class by default

Definitions of derived classes:

Access modifier class derived class Name: Parent class name


Member List


In general, only newly added members of derived classes are defined in the member list of a derived class

When designing derived classes, you should be aware of:

① derived classes can form all other members except instance constructors, destructors, and static constructors, regardless of the accessibility of these base class members

② derived classes can add new members based on the actual accumulation of inheritance, but derived classes cannot remove the definition of a member of an inherited class

③ derived classes can make hidden members inaccessible directly in derived classes by declaring a base class member with the same name (data member) or a new member of the signature (function member).

(3) member access for derived classes

① a member declared as private in a base class can be inherited by a derived class, but cannot be accessed by a derived class member and a derived class user

A member declared as protected in a ② base class can be accessed by a derived class member but cannot be accessed by a derived class user

④ a member of a base class declared as protected internal can be accessed by a member of a derived class in the same program

⑤ a member of a internal in a base class declaration can be accessed by a derived class member and a derived class user in the same program

⑥ the members declared as public in the base class are accessed equally unrestricted in the derived class

(1) constructors for derived classes

The constructor of the derived class is designed to account for the initialization of the new members of the derived class and the data members inherited by the base class, by default, when an instance of the derived class is Pathbreaker, the parameterless constructor of the base class is called.

The constructors for derived classes are as follows:

Public derived class name (argument list): Base (the parameter list of the base class constructor to invoke)


function body


There are two forms of declaring a constructor without a function initialization statement:

Form One

Public derived class name (argument list)//non-parametric constructor for implicitly calling base class


function body


Form Two

Public derived class name (parameter list): Base ()//display the parameterless constructor that calls the base class


function body


When you create an object of a derived class, the constructor of the base class is called before the constructor of the derived class is called

When you destroy a derived class object, the destructor for the derived class is called first, which is an article-by-article destruction of the inner layer.

(2) Polymorphism

The same operation applies to instances of different classes, and different types will be interpreted differently to produce different structures, that is, polymorphic.

Implementation of polymorphism through inheritance in C # is done by hiding the members of the base class

To hide a base class member:

① for data members, you need to declare a new member of the same type and use the same name: For a function member, you need to declare a new function member with the same signature

② you declare a member of the same name in a derived class to hide the members of a base class, you need to use the new modifier to decorate

class person//base class definition

{ {

public string name;;

protected int age;;

public void print ()

{ {

Console. . WriteLine ("I am a person.");

} }

} }

Class Student:: Person//derived class definition

{ {

Internal string Sno

7.5.6 polymorphism


{{get;; set;}

public string Smajor

{{get;; set;}

new protected int age;; Hide base class data member Age

New public void print ()//Hide base class method Print

{ {

Console. . WriteLine ("I am a student.");

} }

} }

① access to the base class is a hidden member, you can use the base class access expression, and the base class access expression is as follows:

Base class member name

② overriding a member of a base class

If there is a reference to a derived class object, using the type quasi-conversion method to convert the reference to a base class type, you can go back to the reference of the base class part, in the following format: (base class name) derived class object name, similar to the method of coercion type conversion of data, through forced conversion to obtain some corresponding function

③ a reference to a derived class object is converted to a rib to access the derived class, the member of the base class is obtained

④ requires a virtual method to provide a method in which a base class reference accesses a "rise to" derived class

The ⑤ virtual method is an instance method that uses the keyword virtual declaration, and the method that does not use the keyword virtual declaration is called a virtual method.

The use of virtual methods to make the base class refer to derived classes requires a cat family condition:

(1) Methods of the derived class and methods of the base class have the same method name and return type

(2) The method of the base class is more than emptiness using virtual declaration as virtual method

(3) The method of the derived class needs to use the override annotation as the Overwrite method

You need to be aware of the use of virtual and overwrite methods:

(1) The virtual and overwrite must have the same accessibility

(2) cannot overwrite static method and virtual method

(3) Methods, properties, indexes, and events can be declared and overwrite using vitrtual and override

(4) Overwrite method can appear at any level of inheritance

When you use the base class reference for an object to electrophoretic a overridden method, the invocation of the method is traced along the derived hierarchy to the most recent derived version of the drop of the tag override, or the smallest version of the backup sequence.

    1. 1. Partial Classes

If the content of a class is long, you can split the declaration of the class into several parts, each part called a partial class.

(1 each partial class declaration contains declarations of class members that can be in a file or in a different file.

(2 when splitting a class into several partial class declarations, each part must be marked as partial class Instead of a separate keyword class .

(3 except that you must add a type modifier, partial , the declaration of the partial class is the same as the normal class declaration

The following is a general declaration of a partial class:

Partial class Partclass{{

Members 1 1 the statement

Members 2 2 the statement


} }

Partial class Partclass{{

member N N the statement

member N n+ +1 1 the statement


} }

partial class declarations that comprise all classes must be compiled together, and these partial classes, declarations, and declarations should have the same meaning, and the parts of the partial class must have the same accessibility, such as public , Private and so on.

    1. 2. Abstract class

An abstract class is a class that is decorated with the abstract keyword.

? The interior of an abstract class may include non-implemented virtual parties that use the abstract adornment

method, called an abstract method.

An abstract class is an incomplete class that can only be used as a base class to derive other classes, which

The abstract methods contained in must be overridden in each non-abstract derived class. For example:

Abstract Class A/a

{ {

public abstract void F F (); Abstract method F F

} }

Abstract class B B:: A A//abstraction b b

{ {

public void G g () {}

} }

Class C C:: b b//non-abstract class C C

{ {

public override void F F () {//Overwrite abstract method in base class F F

Actual implementation of F

} }}

When using abstract classes, be aware that:

① Abstract classes cannot be instantiated directly, and using the new operator with an abstract class can result in compile-time errors;

② allows, but does not require, abstract classes to contain abstract members, but classes containing abstract members must be declared as abstract classes;

③ cannot use the sealed modifier when declaring an abstract class;

④ when deriving non-abstract classes from abstract classes, these non-abstract classes must specifically implement all the abstract members that are inherited, thus overriding those abstract members;

⑥ for each abstract class, you should provide at least one specific type of inheritance.

    1. 3. closed class

If the class definition is decorated with the sealed modifier, the class is a sealed class. A sealed class can only be used as a standalone class and cannot derive from a sealed class from another class. If a sealed class is specified as the base class for other classes, a compile-time error occurs. General definition of sealed class:

Sealed class name


Member List


Sealed classes cannot be declared as abstract classes at the same time.

When a virtual function member of a sealed class instance is called, it can be converted to a non-virtual call to process.

You can use a seal to restrict developers from extending certain specified frames.

If the class meets the following conditions, it should be sealed:

The ① class is a static class;

The ② class contains inherited protected members with security-sensitive information;

The ③ class inherits multiple virtual members and seals the development and testing overhead of each member

Significantly larger than the seal of the entire class;

The ④ class is a property that requires a quick search using reflection. Sealed properties can be

Improves the performance of reflection when retrieving properties.

Do not declare protected members or virtual members in sealed classes. Because if the class is sealed, it cannot have a derived class. Protected members can only be accessed from derived classes, and virtual members can only be overridden in derived classes.

    1. 4. Static Class

A class declared with the static modifier is called a static class. A static class is sealed, cannot be instantiated, cannot be used as a type, and can contain only static members.

The following rules are required when using static classes, which cause compile-time errors when they are violated:

① static classes cannot contain sealed or abstract modifiers;

② static classes cannot explicitly specify a list of base classes or implemented interfaces, which implicitly inherit from the object class;

③ static classes can only contain static members;

④ a static class cannot contain a member of the declared accessibility of protected or protectedinternal.

Static classes do not have an instance constructor. A static class can contain static constructors. If a non-static class contains static members that require important initialization, you should also define a static constructor. A member of a static class does not automatically become static, and the member declaration must explicitly include a static modifier (except for constants and nested types).

For example:

Using System;

public static Class Temperatureconverter


public static double CelsiusToFahrenheit ((Stringtemperaturecelsius))


double Celsius = = Double. . Parse ((TemperatureCelsius);

Double Fahrenheit = (Celsius * 9 9//5 5) + 32;

return Fahrenheit;;


public static double FahrenheitToCelsius ((Stringtemperaturefahrenheit))


Double Fahrenheit = double. . Parse ((TemperatureFahrenheit);

Double Celsius = (Fahrenheit--32) * 5/9;

return Celsius;;



Class Testtemperatureconverter


static void Main ()


Console. . WriteLine ("Please select the Convertordirection");

Console. . WriteLine ("1. Celsius--> Fahrenheit. ");

Console. . WriteLine ("2. Fahrenheit--> Celsius. ");

string selection = = Console. . ReadLine ();

Double F, C = 0;

Switch ((selection))


Case "1":

F =temperatureconverter. . CelsiusToFahrenheit (Console.. ReadLine (());

Console. WriteLine ("Temperature infahrenheit: {0:F2}", F);


Case "2":

C = Temperatureconverter. . FahrenheitToCelsius (Console.. ReadLine (());

Console. . WriteLine ("Temperature in Celsius:{0:f2}", C);



Console. . WriteLine ("Please select Aconvertor.");





    1. 5. differences in class and structure

(1) Different data types

A struct is a value type: A value type Object allocates storage space in the stack, and all base types are struct types

Class is a reference type: The reference type instance allocates storage space in the heap

Structural processing as a small object of accumulation, while classes deal with a business logic

Structured value types, so assignments between structs can create new structures, whereas classes are reference types, and assignments between class instances are just copy references


Both the structure and the base type of the class are Oblject

The struct object is allocated on the stack, not on the heap, and if new is not applied, the field remains unassigned and the object is not available.

(2) Inheritance '

Structure: cannot inherit from another struct or class and cannot be inherited by itself

Class: A class can be fully extensible unless it is declared as sealed, inheriting other classes and interfaces, and can be inherited by itself

Structs can inherit interfaces, and syntax is the same as class-inheriting interfaces. For example:

Interface iimage{

void Paint ();

struct Picture:: iimage{

public void Paint () {

Painting Code goes here


private int x, y, z;; Other structs Members

} }

(3) Internal structure

Structure: Adding a constructor has no effect on the system-generated lunch constructor; Constructors must complete initialization of all members of the struct; there is no ambiguity of the sealed; there is no abstract and no modifier; you cannot have the protected modifier, you can not apply the new initialization. Initializing an instance field in a struct is an error

Class: The system will not generate a default parameterless constructor when adding a constructor, there are destructors, you can use abstract and sealed have protected modifiers, you must use new initialization

① Stack space is limited, for a large number of logical objects, creating a class is better than creating a structure

② structures represent lightweight objects such as points, rectangles, and colors

③ classes are the best choice when it comes to expressing abstract and multi-level object hierarchies

④ most cases when the type is just some data, the structure is the best choice

2017-9-23c# Notes (index, event, operator, this accessor, derivation, partial class, abstract class, enclosing class, Static class, class and struct)

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.