C # Basic Summary.

Source: Internet
Author: User
Tags access properties modifiers

Classes and Members

A class is an abstract description of the properties and behavior characteristics of a set of objects, which are instances of the class.

The class is abstract and the object is concrete. Abstraction is a selective neglect.

Encapsulation: The combination of data and methods, and control of access visibility.

Allows the control---to access the object only through public methods. Changes---the types of private objects that are allowed to change do not affect the use of objects.

Static data describes the information for all objects of a class.

Static methods can access static data only, and access to objects through classes. The method is public and the data is private.
Declaring an object of a class does not create an object of the class-Create an object using the new operator.    Then use the object. method to process the data. The This keyword points to the current object (the current class)---especially useful when names in different scopes identify conflicts.

Class Bankaccout

{

... public void SetName (string name)

{

THIS.name (refers to the private field) = name;

}
private string name;

}
Access modifiers: Public can be accessed only if they know where the namespace is located. Private is visible only to the class or struct in which it resides.
Constant: is a symbol that represents a constant number of values.

Field: Represents the value of a data, which is either read-only, or read-write and can be divided into static fields and instance fields. Initialization is optional, the initialized value must be determined at compile time, and the field value of the struct cannot be initialized. A read-only field must be declared or initialized in a constructor, not necessarily at compile time, and the value cannot be changed.

Method: is a function that changes or queries a type (static method) to learn the state of an object (instance method). Methods generally require read-write types or fields of objects. Static methods can only access static data (fields)


Constructors and destructors
The constructor is first a method.

1. Allocating memory: allocating memory from the managed heap using the New keyword

2. Additional members of the initialization object (method table pointers and internal reserved fields)

3. Initialize the object with the constructor-use the name of the class followed by parentheses.

The CLR requires that each class define at least one constructor. (if not, the compiler automatically creates default constructors) the default constructor features: Pubic access level, same name as class, no return type (including void), no parameters, and all fields are initialized to 0,false,null.

Constructors can be overloaded (same scope, same name, different parameters, can be implemented in different ways to initialize objects, can have different access restrictions) overloaded constructors may contain duplicate code.

struct constructor: The compiler always generates a default constructor, and the default constructor initializes all fields to 0. A constructor declared in a struct does not automatically initialize a field to 0, must initialize all fields, cannot declare a default constructor, and cannot declare an access modifier to a PROCTECD function.

A private constructor can organize the creation of an object, not allow new instances to be instantiated using new, and a static method can use this method without instantiating a class. static method invocation.

Static constructors are used to initialize static fields of a type. (cannot contain access modifiers; must be parameterless; By default, there is no static constructor, and there can be only one static constructor for the definition; inline initialization automatically generates constructors.) Overloading of static constructors is not supported.

The access limit for a static constructor is private, and its invocation is the responsibility of the CLR. Object lifetime Create object: Use the New keyword to allocate memory, and use the constructor to initialize the object in the allocated memory. Use object: The method that invokes the object. Destroying objects: memory is recycled.

Local Variables---A variable destructor defined in a method is a mechanism for implementing object cleanup.

Methods and parameter invocation methods call this method in the same class-the name of the method followed by the argument list and parentheses. Call a method defined in another class--you must specify both the class that contains the method, and the method that is called must declare the appropriate access modifier, such as public.

Nested calls--you can call other methods in the method.

Local variables: Created when the method starts executing, is private to the method, and the exit method is destroyed.

Shared variables: When variables are defined at the class level, they can be accessed concurrently by multiple methods.

Scope conflict: The compiler does not warn when there is a naming conflict between the authorities and shared variables. Precedence enables local variables within a method to be specified with this by using a shared variable. Declaration and invocation parameters: declaring parameters--placing parameters in parentheses after the method name, and defining parameter names and types for each parameter. Method of calling parameters--Specify a value for each parameter. Pass-through parameter value types are passed by value--a copy of the value type instance is passed to the method, and the instance in the calling method is not affected.

Reference type value pass--when the argument is passed by passing a reference to the object, the reference (pointer) itself is passed by value, and the method can alter the reference object.

Reference parameter: A reference to the memory address of the parameter. Use reference parameters: Use the REF keyword when declaring and invoking in a method;

The value and type of the variable must match; the change to the parameter within the method affects the caller; The value of the parameter must be specified before the method is called.

Output parameters: Parameter values are not passed into the method, and are used to pass values outside the method instead of methods, and do not require an initial value of the out variable length parameter: Use the params keyword, the last declaration in the argument list, declare a one-dimensional array, compile-time matching checks, and always pass by value.

Eg:static long addlist (params long[] v)

{

Long total, I;

for (I=0,total =0;i<v.length;i++)

Total+=v[i];

return total;

}

static void Main ()

{

Long x = Addlist (63,21,84);//This place can continue adding parameters as long as it is not longer.

}

Recursive method: method to call itself

eg

public int factorial (int n)

{

if (n<=1)

return 1;

Else

return factorial (n-1) *n;

}

Methods and operator overloading
Method Overloading: A method that has the same name in the same class. Differentiated by the parameter list;
Method signature: In a class, the signature of a method must be unique, such as the name of the method, the parameter type, the number of arguments, the order of the parameters, and the modifier of the parameter.

There is no effect on the signature: the name of the parameter, the return type of the method, whether the params is used, or only the difference between ref and out. Use overloaded methods: conditions: You need a similar method with different parameters; To add new functionality to existing code. Do not misuse overloading (debugging, maintenance more difficult)

Overloading of operators (overloading of constructors)

eg

Class Vector

{

public double x, y, Z;

Public Vector (double x,double y,double z)

{//Initialize three fields in a class

This.x=x;     This.y=y; This.z=z;

}

Public vector (vector rhs)

Overloading of the {//constructor, assigning the value of the class to the parameter RHS

x=rhs.x;      Y=rhs.y; Z=rhs.z;

}

public override string ToString ()

{

Return "(" +x+ "," +y+ "," +z+ ")";

}

public static vector operator + (vector lhs, vertor RHS)//Operator's overloaded operator returns vector type

The type of the {//parameter is the same as the return type of the operator.

Vector result = new vector (LHS);

result.x+=rhs.x;

Result.y+=rhs.y;

Result.z+=rhs.z;

return result;

}

static void Main ()

{

Vector Vect1,vect2,vect3;

Vect1 = new Vector (3.0,3.0,1.0);//instantiation and initial value

Vect2 = new Vector (2.0,-4.0,-4.0);

VECT3 = vect1+vect2;//c# The default is not to support the addition of two objects, but overloaded can be.

Console.WriteLine ("Vect1=" +vect1. ToString ());

Console.WriteLine ("Vect2=" +vect2. ToString ());

Console.WriteLine ("Vect3=" +vect3. ToString ());

Console.ReadLine ();

}

The conversion operator method must be public and static. Display conversion with explicit keyword hermit conversion using implicit keyword

Properties and indexers
A property is an efficient way to (encapsulate) internal information, protecting a field inside a class. The simplicity of use, flexibility, and the ability to validate data before changes can transparently expose the data in the class, and when data is changed, actions can be taken, such as raising events.
property provides field-like access: Provides read access using the Get accessor method, and provides set access using the set accessor method.

eg

Class Button

{

public string Caption//property, which accesses the private field through the property method.

The Caption property encapsulates the following caption private fields

{

Get{return caption;}

Set{caption=value;}

}

Private String Caption;//field secret field

}//Using Attributes

Btton button = New button (); button. cation = "button";//Assign a value to a property
property, Field Difference: property is a logical field--get accessor method can return a computed value.

Similarity: The syntax used is similar. Different: properties are not values, they do not have addresses (essentially manipulating fields, encapsulating fields) properties cannot be passed as ref and out parameters of the method.

Attribute and method Difference: similarity--both contain the code to execute, can be used to hide the implementation details, can be added virtul,abstract,override and other modifiers. Different---Syntax: attributes do not use parentheses, semantics: The return value of a property cannot be empty, nor can it use any number of arguments. Static properties belong to a class and can only access static data. The access modifier for the property:

For example, declaring a get accessor method as public, declaring a set accessor method as protected (which can only be assigned within a class or within a derived class) indexer: An array of intelligent values. Indexers provide an array-like access to an object-useful when a property can have multiple values.

eg

Class Sample

{

public int this [int i]//this is the type of the indexer name int is the indexer value or the value assigned to him.

{

Get{return This.data[i];

}//returns an array of data I coordinates

Set{this.data[i] = value;} Assigning value values to the data field

}

private int data[] = new Int[10];//field integer array

}//using indexers

Sample mysample = new sample (); mysample[0]=1;//0 is passed to the I in this [int i] and then the indexer assigns 1 to the data array ...

int a = Mysample [2];//calls get access indexers and arrays are similar: all use array syntax is different: indexers can use non-shaping subscript, (indexers can be overloaded, you can define several indexers that use different index types), it is not a variable, there is no actual storage location, No, No. Passing an indexer as a ref and out parameter


The difference between an indexer and a property
Same: Both get and set accessor methods, no addresses, and return types cannot be empty: indexers can be overloaded, indexers cannot be statically defined indexers, you need to have at least one index parameter specified for each parameter, you cannot use the ref and out parameter modifiers.


Delegates and events
Delegate: Used when passing methods to other methods. One method needs to operate on another, and the second method needs to be passed as a parameter to the first method.
Use a delegate--define the delegate to use, which tells the compiler what type of method this delegate type represents, and then creates one or more instances of the delegate. Declaring a delegate is defining a type that encapsulates a definition of a method that has a specific set of parameters, which is the return value.

delegate void MyDelegate1 (string s);//A delegate is declared for a method that takes a parameter of type string and that the return value is null. A delegate is the equivalent of defining a new class, where a delegate can be defined anywhere the class is defined. Instantiate delegate: Creates a delegate object using the new operator. A delegate's constructor always has a parameter, which is the method referenced by the delegate.

Eg: Instantiate a delegate as

(instantiating) static methods in the MyClass class

HelloMyDelegate1 a=new MyDelegate1 (Myclass.hello)//Instantiate the delegate as an instance method in the object p of the MyClass class

Amethod MyClass p=new MyClass ();

MyDelegate1 B = new MyDelegate1 (P.amethod);

Invoking a delegate//based on the preceding declaration and instantiation procedure, the following statement invokes the static method hello in the MyClass class, uses the parameter Worlda ("World"), and the instance of the delegate's feature delegate can be an instance method or a static method on any object of any type. As long as the feature of the method matches the characteristics of the delegate.


Multicast delegates: Delegates can include multiple methods, which can be called sequentially to call multiple methods consecutively, and the signature of a delegate must return voidmydelegate a,b,c,d;a= new MyDelegate (Foo); b= new MyDelegate (Bar); c = A +B;//A and B are combined into C delegate, C is multicast delegate d = c-a;//subtract a delegate from C, then D delegate only references B delegate Bar Method a+=b;//a is multicast delegate a-=b;//a and becomes unicast delegate
Event-the communication medium between objects, using delegates in. NET to encapsulate the event. The delegate type that declares the event. Plus the event keyword plus a delegate.

eg

public delegate void Mouseclicedeventhandler ();
public class Mouse

{

public static event Mouseclickedeventhandler mouseclicked;

(Mouseclicked is the name of the event) ....} Register to Event: Register to Event via + = (Combine) and unregister to event via-= (remove).

private void mouseclicked () {..} constructor function

Mouse.mouseclicked+=new Mouseclickedeventhandler (mouseclicked//constructor method);

Mouse. Mouseclicked-=new Mouseclickedeventhandler (mouseclicked);

Trigger Event: Checks if there is a client registered to this event (if the field representing the event is empty, indicating there is no client), the event is triggered by invoking the delegate of the event.

if (mouseclicked!=null) mouseclicked ();

At this point, the event is triggered by invoking the delegate of the event to handle the event when the delegate is used, and the event uses the delegate: When you need a C-style function pointer, you need to handle a single callback, and the callback is specified during a method call or construct, rather than through the Add method. Use event: The client registers the callback function with the Add method, and there may be multiple interest in the object for the event, and it is desirable for the end user to be able to easily add the listener to the event in the designer.


Inheriting derived classes: You can add your own fields and methods by inheriting the fields and methods from the base class. Derived classes build on base classes to avoid duplication of code

Class Person

{

String name;

int age;

public void Birthday ()

{age++;}

}

Class student:P Erson

{int id;}

Class Employee:person

{Double salary;}

Class Gradute:student

{string Advisor;}

The objects in the derived class can use the functionality in the base class.

Student s = new Student () S.birthday ();

A derived class can have only one base class, and multiple inheritance is not allowed. Derived classes can access members of the base class that have access level protected, and other classes are not. A method of a derived class can call a method of the base class using the base keyword.

Class Person

{

public void Print ()

{

Console.WriteLine (name);

Console.WriteLine (age);

}....}

Class Student:person

{

Public new void Print ()

{base. Print ();//

Console.WriteLine (ID);

}... In a derived class class that has the same name as a method in the base class, there is a method in the base class to call at this time base.

Constructors and inheritance creating an object of a derived class should initialize the entire object-first the part of the base class, and then the part of the derived class.

The constructor of the derived class should call the constructor of the base class-the syntax for using: Base () before the body of the constructor;

--The base class

Class Person

{

Public person (string Name,int age)

{...}

...}

Class Student:person

{

int id;

Public Student (string name,int age,int ID): Base (Name,age) calls the constructor in the base class and passes two arguments, only in order to initialize the fields in the base class.

{this.id =id;}

}

Base class constructors can be added without base () when they are default.

Defining a virtual method derived class sometimes requires a method that overrides a base class when a method in the base class should be defined as a virtual method, declared with virtual.

Class Token

{

Public virtual string Name () {:}

}

The method in the derived class override must be strictly constrained in the base class.

Override using the Override keyword.

Class Commentoken:token

{public override string Name () {}}

You can continue to override the override method;

No, it's not. The override method is declared as static or private;

The override method cannot change the access properties of the virtual method.

Hide inherited members: Use the new keyword to indicate that you can hide virtual and non-virtual methods by deliberately hiding them.

Class Person

{

int id;

public void SetId (int id)

{this.id = ID;}

}

CLSS Student:person

{

int id;

Public new void SetId (int id)

{this.id =id;}

}

Sealed classes cannot be used as base classes and cannot be derived from sealed classes (sealed)

Abstract abstract classes cannot be instantiated, but can still use their references. The class that contains the abstract method must be abstract.


Polymorphic
With inheritance, a class can be used as a variety of types: it can be used as its own type, any base type, or as any interface type when implementing an interface. This is known as polymorphism.
A reference to a base class can point to a derived object

Class Person

{

public string name;

public int age, ....

}

Class Employee:person

{

public double salary;.

}

Employee E = new Employee ();

Person P =new Employee (); a reference to a base class can point to a derived object Is-a type compatible. The type of reference determines the allowed access-only members of the base class can be accessed through a reference to a base class.

Person p = new Employee ();

P.name = "Bob";p. Age = 23;p.salary = 42000.00//This is not the case. You can pass an object of a derived type to a parameter of the base class reference.

BOOL Checkage (person P)

{return p.age>=21;}

Sometimes the same method appears in the inheritance hierarchy-each class can provide its own version, and a method of the same name in a derived class can hide a method of the same name in the base class, referring to a method in the derived class. Binding: A method can be called through a reference to a base class. You must determine the version of the base class or derived class that is being called, and the procedure called binding.

void Evaluate (Employee e)//pass the parameters of the base class

{e.promote ();//The same name method in the base class}

Faculty f= new Faculty ();//derived class instantiation

Staff S = new staff ();
Evaluate (f); Evaluate (s);

Static binding: A method that uses the base class.

Dynamic binding: Virtual, override depends on whether the parameter being called is a base class or a derived class, and if it is a base class, call the base class and vice versa. A reference to a base class can access only the members of the base class, even if it refers to an object of a derived class. Use the New keyword

--the method in the derived class is the method that hides the base class;

--the method of static binding is used to determine the runtime method;

--Determine the method used based on the type of the reference variable.

Use the Override keyword

--a method in a derived class that overrides a method in the base class;

--the method of dynamic binding is used to determine the runtime method;

--Determines the method used based on the type of object.

Interface interfaces define a specification, also called a contract. Use the keyword interface to create an interface.

An interface can contain methods, indexers, properties, events. However, the inclusion of an implementation is not allowed, and other types of members are not allowed.

Interface IMyInterface

{

void Process (int arg1,double arg2);

float this [int index]{get;set;}

String Name{get;set;}

Event MouseEventHandler Mouse;

}

The default access level for members of an interface is public and does not need to be public. Class can support interfaces--declares Class:interface, must implement all members of an interface

(This is the implementation of a method body that must have a member method in the interface in the Class).

To implement an interface member, the corresponding member in the class must be public, non-static, and have the same name and signature as the interface member, and the method of implementation can be virtual or non-virtual;

The properties and indexers of a class can be additional accessors defined for a property or indexer defined on an interface. An interface reference can point to an object that implements an interface, access restrictions, access to only the members defined in the interface (interfaces and abstract classes cannot be instantiated) ifigter F = new Soldier (); Multiple classes can implement the same interface, which can be implemented using different methods. Write a method through an interface-this method can be used for any object that implements an interface. A class can implement multiple interfaces at the same time-separated by commas, a method must be defined for all interfaces. A class that implements a derived interface must implement all of the methods-the interface-defined methods of all interfaces on the inheritance hierarchy. (a specific implementation of all the members in the interface is given in the class.)


String ToString Rewrite

Tostringpublic class Person

{

String name;

int age;

public override String ToString ()

{

Return String.Concat (Name, ":" Age.) ToString ());}

}

Example:

public class UserInfo

{

private string UName;

private int uage;

Pulic string UserName
{Get{return uName;} }

public int Userage

{Get{return uage;} }


Public UserInfo (String Umae,int uage)

{this.uname = UName; This.uage=uage;}
public override string ToString ()

{

return string. Concat (UName, ":", uage);//return "You have called my own ToString Method! "}

}

Class Program

{

static void Main ()

{

UserInfo u = new UserInfo ("Wangli", max): U.tostring ();

Console.WriteLine (U.tostring ());

}

Numeric type format string:

c indicates that the currency format D means that the decimal format e means the scientific notation F indicates that the fixed-point format p represents the Percent format x represents the hexadecimal format

DateTime.Now.DayOfWeek.Tostring ("D")//return enum type

Console.WriteLine (DateTime.Now.Tostring ());

Composite format composite formatting supports constructed strings that contain multiple formatted objects;

Methods to support composite formatting: static method of String

Format,consol.writeline,textwrite.writeline (writes the output string to a stream or file)

Composite formatting: Format strings in indexed composite formatting use numbers in braces to identify replaceable parameters

eg

String MyString = String.Format ("On{0},{2}yerars old.", DateTime.Now, "Tom", 35);

Console.WriteLine (MyString);

Composite formatting: Formats can add formatting information to the curly braces to add more control to the final formatted output: The ToString method in the IFormattable interface that is called when the type of the replacement parameter is implemented, or if this interface is not implemented, the ToString method is called without a parameter.

Parseeg:

1.

String snum = "58";

int iNum = Int. Parse (Snum);

Console.WriteLine (INum);

2.

It is recommended to use string snum= "", int inum;if (int. TryParse (Snum,out iNum)) {
Console.WriteLine (INum);} else{Console.WriteLine ("Not numbers!!! ");
}

String Basics
The string class is easy to use, and C # provides the string keyword as a synonym for System.String. String is a reference type--created with the new keyword. Character constants can be automatically converted to string objects (without new).

Escape sequence: Use the escape character/.

You can create a character constant that is not escaped: string preceded by @string [email protected] "c:/windows/config";

String provides a read-only length property of string s= "Hello";

int i=s.length;

The string type provides a read-only indexer index from zero, and the document corresponds to chars math, which should be used in accordance with the syntax of the indexer string s= "Hello"; char c = s[4];s.toupper ();

Sorting and inversion you can copy the character of a string into a character array by using the ToCharArray method;

It can be sorted and reversed by the sort and reverse methods in the array class. String invariance There is no way to change the contents of a string, actually creating a new object that represents the new value. StringBuilder represents a variable sequence of characters. Provides a way to change its content. Allows the user to set the capacity.

StringBuilder text=new Stringbulider ();

Text. Append ("DFD") text. Append () return text. ToString ();

eg

static void Main (String)

{

Stringbulider text=new Stringbulider ();

for (int i=0;i<100;i++)

{

Text. Append ("character" +i.tostring ());

Text. AppendFormat ("{0}", i.ToString ());//

Text.append (String.Format ("{0}", i.tostring);

}

String Result=text. Tostring ();}

}

Regular expressions
The Regex class creates regular expressions for the Regex method, the--ismatch method, and the power of the Replace method pattern-matching regular expression is not reflected in the match of the specific character, but on the pattern match of the character type

C # Basic Summary.

Related Article

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.