C # learning records,

Source: Internet
Author: User

C # learning records,

In the twinkling of an eye, I haven't changed my mind for a few months. After I took a note of C # a few months ago, I recorded some important ideas.

 

1. Print

Console. WriteLine (); print

Console. ReadKey (); press a key to continue execution

Console. ReadLine (); // The program is paused when the user inputs the text. After the user inputs the text, press enter to return the user input.

Example:

String s = Console. ReadLine (); read strings, so it cannot be received by other types.

 

 

2. Data Type:

Value Type: int, float, double, char, byte, Boolean, enumeration

Reference Type: DateTime, string, all classes

 

Type conversion:

Value Type: automatic conversion from small To large, forced conversion from large To small, (type), Convert. ***()

Reference Type: It can be converted only when there is an inheritance relationship.

Convert to string: ToString ()

Type conversion: cast strong conversion (digits are different and may be lost)

Convert Converts data meaning

The C # string is the same as the OC string, and is different from the C string. do not consider the final \ 0

 

 

'A' is of the char type, and "a" is of the string type.

@ "\\\\" @ Indicates that \ In the string is not considered as an escape character.

 

 

3. string processing

· In C #, a single character is enclosed in single quotes as char type ('A'). It can only be placed in single quotes and can only contain one character.

· A single character can also be expressed as a string or a string of 0 characters.

· Use the s. Length attribute to obtain the number of characters in the string.

· String can be viewed as a char read-only array. Char c = s [1]; example: traverse each element in the output sting.

· The character string in c # has an important feature: immutable. Once declared, the character string can no longer be changed. Therefore, you can only use Indexes

Read and modify the char at the specified position.

· If you want to modify char, you must create a new string for a long time and use the s. ToCharArray () method to obtain

Char array. After modifying the array, call the new string (char []) constructor to create a char array string. I

Once the string is created, the modification of the char array will not change the string. Example: replace A with.

 

 

 

String immutable (immutable In the allocated memory block)

String s1 = @ "hello ";

Char [] chars = s1.ToCharArray ();

String s2 = new string (chars );

In this case, s2 is aello, and s1 remains unchanged. Therefore, only a char array data is copied, which is irrelevant to the source data.

 

For example, string s = "abc"; s = @ "123"

The last value has changed, but it is not

Distinguish between variable names and variable points. There can be many strings in the program, and then the string variables point to them. The variables can point to other strings, but the strings themselves have not changed. The immutable character string refers to the immutable character string in the memory, rather than the variable.

 

 

4. Common functions of string classes

 

1)

· ToLower () to obtain the string in lowercase.

· Note that the string is immutable, so these functions do not directly change the content of the string, but return the modified value in the form of a function-return value. S. ToLower () and s = s. ToLower ()

· ToUpper (): Obtain the string in uppercase format: Trim () removes the white space at both ends of the string.

· S1. Equals (s2, StringComparison. OrdinallgnoreCase), two strings for case-sensitive comparison

Ignore: Ignore, Case: Case

= Is case-sensitive comparison, while Equals () is case-insensitive comparison.

 

 

2) split the string

String [] str = strings. Split (','); Splits a string into a string Array Based on the specified delimiter

 

Splits the string into a String Array Based on the specified char delimiter (when RemoveEmptyEntries is used for options, the blank string in the result is removed)

String str1 = @ "aa, bb, cc, dd"; an empty string is displayed.

String [] str = strings. Split (new char [] {','}, StringSplitOptions. RemoveEmptyEntries );

 

Splits a string into a string Array Based on the specified string delimiter (same as above)

String [] str = strings. Split (new string [] {"aa"}, StringSplitOptions. RemoveEmptyEntries );

 

 

3) Replace string

String. Replace ("a", "B"); Replace all a in string to B.

Obtain the substring:

String. Substring (n); truncates string strings from the nth position to the end, including n

String. Substring (n, m); the length of the string starting from the nth digit is m (an error occurs if m exceeds the string length), including n

 

 

4) return bool value: string. Contains

Contains (string value) determines whether the string Contains a substring value

StartsWith (string value) determines whether the string starts with a substring value.

EndsWith (string value) determines whether the string ends with a substring value

Return int

IndexOf (string value) position where the substring value first appears

 

 

 

 

 

 

Enumeration, which is no different from other languages

The significance of enumeration is to limit the value range of a variable.

Enum sender {a, B}

 

 

Foreach (string name in names) {}; traversal, and for, see more

 

 

Static void function (params string [] values ){};

The params variable parameter must be the last parameter in the form parameter table.

 

 

Function overload: The function name is the same, and the parameters are inconsistent. It can be used by two functions and has nothing to do with the return value (not rigorous)

 

 

 

Function ref and out parameters

Function parameters are passed by default, that is, "copy one copy"

While ref is to pass itself in, not to copy

 

Static void Main (string [] args)

{

Int age = 20;

1: IncAge (age );

2: IncAge (ref age );

Console. WriteLine (age); // 1: The result is 20, because only the parameter value is passed. 2: The result is 21,

Console. ReadKey;

}

1:

Static void IncAge (int age)

{

Age ++;

}

2:

Static void IncAge (ref int age)

{

Age ++;

}

 

The ref must be initialized first because it is a reference, so it must be "available" before it can be referenced. The out is an internal value assigned to the external, so it does not need to be initialized, and the external Initialization is useless.

In the ref Application Scenario, external values are changed internally, while out values are internally assigned to external variables. out values are generally used in scenarios where a function has multiple return values.

 

 

String str = Console. ReadLine ();

Int I;

Int. TryParse (str, out I); // the return value of conversion is true or false.

 

Ref application, such as exchanging two values

 

 

5. Constructor

 

· Constructor is used to create objects and can initialize objects in constructor.

· Constructor is a special function used to create objects. The function name is the same as the class name and has no return value. It is not used for void.

· The constructor can have parameters. When a new object is added, the function parameters can be passed.

· Constructor can be overloaded, that is, there are multiple constructors with different parameters.

· If no constructor is specified, the class has a default no-argument constructor.

If a constructor is specified, no default constructor is available. If no constructor is required, you need to write the constructor by yourself.

For example:

Static void Main (string [] args)

{

Person p1 = new Person ();

Person p2 = new Person ("");

Person p3 = new Person ("a", 2 );

Console. ReadKey;

}

Class Person

{

Public Person ()

{

 

}

Public Person (string name)

{

 

}

Public Person (string name, int age)

{

 

}

}

 

 

 

 

 

 

 

 

 

 

The opposite can be called an instance of the class, and the field is the status of the class.

Three object-oriented features: encapsulation, inheritance, and polymorphism.

 

 

 

 

 

 

 

 

 

6. attributes (public and private)

Usage: uppercase letters at the beginning of a property and lowercase letters at the beginning of a field

The difference between a public field and a property. The property can be used to determine the value of an invalid setting.

 

Class person

{

Private int age;

Public int Age

{

Set // assign values

{

If (age> 0)

{

Return; // if return this. Age; causes an endless loop, assign a value to yourself.

}

This. age = value; // value indicates the value assigned by the user.

}

Get // Value

{

Return this. age;

}

 

}

}

 

 

 

 

 

7. Exceptions

Try {

After the error point is executed, it will not be executed.

}

Catch (Exception ex ){

After an error occurs, run the command again.

Console. WriteLine ("data error:" + ex. Message + ". Exception Stack: "+ ex. StackTrace );

}

 

Throw: throw catch: catch

// Custom error Declaration

Else {

Throw new Exception ("custom Exception ");

}

 

 

Const constant: Constant

 

Static variable: static is a global variable and does not require new

Non-static members cannot be called directly in static members.

Example:

Class Person

{

Public static int TotalCount;

Public int Age;

Public static void number ()

{

Console. WriteLine (@ "{0}", TotalCount );

// You can call TotalCount, but cannot call Age.

}

 

Public void Other () // non-static member, CAS calls static member

{

Console. WriteLine (@ "{0}, {1}", TotalCount, Age );

}

}

 

 

 

 

 

 

8. Static class

Static class Person

{}

The new class cannot be a static class. The static class is generally used to implement some function libraries.

 

 

 

 

 

 

 

 

 

 

 

9. namespace

 

When multiple classes have duplicate names, they can be stored in different folders or in different namespaces. You can write the full path when using them.

The current class file contains the Person class.

Another folder named hr or a class inconsistent with the namespace has a class Person

 

When using the Person class in the hr folder in the current class file:

If the class to be used and the current class are not in the same namespace, you need to add using reference

Import the file at the top

Using namespace. hr;

Namespace. hr. Person p2 = new namespace. hr. Person ();

// Like the full path of a file

 

 

10. Index

C # provides the access method based on the indexer.

How to define the indexer: string this [int index]

{

Get {

Return "";

}

Set {}

}

String is the index type, which is a list of parameters in. The index writer write operation is called.

Set code block. Use value inside the set to get the value set by the user.

Run the get code block.

There can be more than one index parameter, and the type is not limited to int. The number of digits can be of any type.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

11.

Project awareness, copying from various places

 

 

String. Empty is a static constant of the string class;

String. Empty is not much different from string = ""

 

String s1 = "";

String s2 = string. Empty;

If (s1 = s2) <br> {

Console. WriteLine ("Exactly! ");

}

// The result is True.

 

String. Empty is the same as string = "", which also requires memory space. Why is String. Empty recommended?

String. Empty only allows the code to be read, preventing code Ambiguity

 

 

 

 

It is used to control whether an object is activated. when an object is activated and its active status is true, its parent node is also active. Similar APIs include:

1) GameObject. SetActive

2) GameObject. activeSelf

3) GameObjectd. activeInHierarchy

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Socket. BeginReceive method (Byte [], Int32, Int32, SocketFlags, AsyncCallback, Object)

 

Syntax

[HostProtectionAttribute (SecurityAction. LinkDemand, ExternalThreading = true)]

Public IAsyncResult BeginReceive (

Byte [] buffer,

Int offset,

Int size,

SocketFlags socketFlags,

AsyncCallback callback,

Object state

)

 

Parameters

Buffer

Byte array, which is the location where the received data is stored.

Offset

The location where the received data is stored in the buffer parameter, which starts from scratch.

Size

The number of bytes to receive.

SocketFlags

A bitwise combination of SocketFlags values.

Callback

An AsyncCallback delegate that references the method to be called when the operation is complete.

State

A user-defined object that contains information about the operation to be received. When the operation is complete, this object will be passed to the EndReceive delegate.

Return Value

Type: System. IAsyncResult

REFERENCE The IAsyncResult of asynchronous read.

 

 

 

 

 

 

Exception

 

 

Exception

Condition

ArgumentNullException

Buffer isNull.

SocketException

An error occurred while trying to access the socket. For more information, see the remarks section.

ObjectDisposedException

The Socket is disabled.

ArgumentOutOfRangeException

Offset is less than 0.

-Or-

The offset value is greater than the buffer length.

-Or-

The size is smaller than 0.

-Or-

The size is greater than the length of the buffer minus the value of the offset parameter.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Socket. BeginReceive method (Byte [], Int32, Int32, SocketFlags, AsyncCallback, Object)

Start receiving data asynchronously from the connected Socket.

Namespace:System. Net. Sockets

Assembly:System (in System. dll)

 

Syntax

 

[HostProtectionAttribute (SecurityAction. LinkDemand, ExternalThreading = true)]

Public IAsyncResult BeginReceive (

Byte [] buffer,

Int offset,

Int size,

SocketFlags socketFlags,

AsyncCallback callback,

Object state

)

 

Parameters

Buffer

Byte array, which is the location where the received data is stored.

Offset

The location where the received data is stored in the buffer parameter, which starts from scratch.

Size

The number of bytes to receive.

SocketFlags

A bitwise combination of SocketFlags values.

Callback

An AsyncCallback delegate that references the method to be called when the operation is complete.

State

A user-defined object that contains information about the operation to be received. When the operation is complete, this object will be passed to the EndReceive delegate.

Return Value

Type: System. IAsyncResult

REFERENCE The IAsyncResult of asynchronous read.

Exception

 

 

Exception

Condition

ArgumentNullException

Buffer isNull.

SocketException

An error occurred while trying to access the socket. For more information, see the remarks section.

ObjectDisposedException

The Socket is disabled.

ArgumentOutOfRangeException

Offset is less than 0.

-Or-

The offset value is greater than the buffer length.

-Or-

The size is smaller than 0.

-Or-

The size is greater than the length of the buffer minus the value of the offset parameter.

 

 

 

Remarks

 

 

Copy count bytes from src to dst. The former begins with srcOffset and the latter starts with dstOffset.

Developers should keep in mindBlockCopyThe method uses offset to access the src parameter, instead of using an index or an array upper or lower limit. For example, if you declare an Int32 array whose upper limit is 0 and lower limit is-50 using the application programming language, then pass the array and offset 5BlockCopyMethod, the first array element accessed by this method is the second element of the array (located at index-49 ). In addition, the first access to which byte of the array element-49 depends on the Edian setting of the computer on which the application is executed.

 

 

 

 

 

 

 

 

 

 

Add and AddRange

 

Add: Add the specified object ...... Medium

AddRange: directed ...... Add an array

-

Use AddRange instead of Add during group operations 

 

With AddRange, we can add things we want to add at one time instead of at one time. This obviously speeds up the process. Almost all windows controls support the Add and AddRange methods.

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.