C # + Asp.net series tutorials

Source: Internet
Author: User
This tutorial is written by referring to the C # and ASP. NET Programming tutorials. If you have any shortcomings, please point out or leave a message on the old cat's ideal BLOG.
First, I would like to explain c #. Here is a rough explanation. For details, please purchase related books or refer to relevant documents. C # has canceled the pointer in c ++ and a large number of operators (:->) used in c ++ are no longer displayed. c # supports ". ". C # has all the features of object-oriented programming languages, such as encapsulation, inheritance, and polymorphism. It is more object-oriented than java, and each type can be considered as an object. However, c # indicates that a single inheritance is allowed, that is, a class does not have multiple base classes. In addition, c # has no global function, no global variable, and no global constant. Everything must be encapsulated in a class.
The following is a small example of a console application:

Using System;
Class MikeCat
{
Public static void Main ()
{
Console. WriteLine ("Mike's old cat c # asp.net tutorials-welcome to the old cat's ideal ");
}
}

In c #, the program always starts from the Main () method. The Main () method must and can only be contained in one class. The type returned by the Main () method can be void (no return value) or int (return an integer representing the application error level ).
The preceding using System is used to import Namespace to indicate the class hierarchy. If you do not need to use using to import a namespace, you must add a namespace before the class name each time you use a class.
C # the input and output of the program are implemented through the Console. Console is a class in the System namespace. Output a string on the screen using Console. WriteLine (), and accept input from the input device using the Console. ReadLine () method.
Program code:
Class MikeCat
{
Public static void Main ()
{
System. Console. WriteLine ("Mike's old cat c # asp.net tutorials-welcome to the old cat's ideal" n ");
System. Console. WriteLine ("Enter the User name :");
String user = System. Console. ReadLine ();
System. Console. WriteLine ("Welcome: {0! ", User );
}
}
The first parameter followed by the string in the parameter table of the WriteLine () method replaces {0 }.
If you want to pass the command line parameter to the application during program execution, the format of the Main () method should be:
Using System;
Public class MikeCat
{
Public static void Main (string [] args)
{
Console. WriteLine ("A total of {0} command line parameters", args. Length );
For (int I = 0; I <args. Length; I ++)
{
Console. WriteLine ("Arg [{0}] = [{1}]", I, args [I]);
}
}
}
Single line comment in c # // and multi-line comment /*...*/
Use constants in c:
Using System
Class MikeCat
{
Public const double PI = 3.14;
Public static void Main ()
{
Console. WriteLine ("the PI value of the circumference rate is {0}", PI );
}
}
Struct is a composite data type used to organize some related data into a new data type.
Using System;
Struct MikeCat
{
Public string Mike; // user
Public uint Age; // age
Public string Email; // email
}
Class mf
{
Public static void Main ()
{
MikeCat zl; // declare the struct type variable zl
Zl. Name = "Mike ";
Zl. Age = 24;
Zl. Email = "mike@hebut.com ";
Console. WriteLine ("Name: {0}, Age: {1}, Email: {2}", zl. Name, zl. Age, zl. Email );
}
}
In c #, the enumeration type (enum) is a set of logically inseparable integer values:
Using System;
Enum WeekDay
{
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}; // Note the semicolon
Class MikeCat
{
Static void Main ()
{
WeekDay day; // declare the enumerated variable day
Day = WeekDay. Tuesday;
Console. WriteLine ("the value of day is {0}", day );
}
}
In c #, each element type in the enumeration type is int byte long short type, and the first element value is 0, followed by 1. In enumeration, you can also assign values to the elements, followed by increments.
Enum WeekDay: byte
{
Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
};

We often use arrays. Here we will introduce the array as a group of data of the same type. When accessing data in the array, you can specify it by subscript. In c #, the array element can be of any data type. The subscript of the array starts from 0, that is, the subscript corresponding to the first element is 0, and then increments one by one. Arrays can be one-dimensional or multi-dimensional.
// A one-dimensional integer array containing six elements;
Int [] mf1 = new int [6]; // specify the array initialization range or the initial value;
// A one-dimensional integer array containing six elements. The initial values are 1, 2, 3, 4, 5, and 6.
Int [] mf2 = new int [6] (1, 2, 3, 4, 5, 6 );
// A one-dimensional string array. If an initial value is provided, the new operator can be omitted.
String [] mf3 = {"c", "c ++", "c #"};
// One-dimensional object Array
Object [] mf4 = new Object [5] {26, 27, 28, 29, 30 };
// Two-dimensional integer array, initial value mf5 [] = 1, mf5 [] = 2, mf5 [] = 3, mf5 [] = 4
Int [,] mf5 = new int [,] {1, 2}, {3, 4 }};
// A 6*6 two-dimensional integer Array
Int [,] mf6 = new mf [6, 6];

Next let's take a look at the traversal of a one-dimensional string array.
Using System;
Public class MikeCat
{
Static void PrintArray (string [] arr)
{
// Print the array element. arr. Length indicates the number of array elements.
For (int I = 0; I <arr. Length; I ++)
{
Console. WriteLine ("arr [{0}] = {1}", I, arr [I]);
}
}
Public static void Main ()
{
String [] arr = {"c", "c ++", "c #"};
// Pass the array as a parameter
PrintArray (arr );
}
}
Program result: arr [0] = c arr [1] = c ++ arr [2] = c #

Let's take a look at the traversal of an integer array of four rows and two columns (4*2:
Using System;
Public class MikeCat
{
Static void PrintArray (int [,] arr)
{
// Traverse two-dimensional arrays through two FOR Loops
For (int I = 0; I <4; I ++) // initializes I as a cyclic variable, and I ++ implements the auto-increment operation for this variable.
// After the for loop meets the conditions, execute I ++ after the loop body is executed once, and then enter the next loop. Simple c syntax. Here is a brief introduction to take care of beginners. (For details, refer to Mr. Tan haoqiang's C language programming book)
{
For (int j = 0; j <2; j ++)
{
Console. WriteLine ("arr [{0}, {1}] = {2}", I, j, arr [I, j]); // print each two-dimensional array element
}
}
}
Public static void Main ()
{
// Main Function
// Pass the array as a parameter
PrintArray (new int [,] {1, 2}, {3, 4}, {5, 6}, {7, 8 }};
}
}
Running result: arr [] = 1 arr [] = 2 arr [] = 3 arr [] = 4 arr [] = 5 arr [] = 6 arr [] = 7 arr [3, 1] = 8


Class is the basic construction block of object-oriented programming. We will introduce it in detail later. Here we will introduce two special classes: object class and string class.
1. object Class
The object class is the alias of the pre-defined class System. Object. It is the base class of all other types. All types in c # are inherited directly or indirectly from the object class. Therefore, an object class variable can be assigned a value of any type.
Int I = 30;
Object obj1;
Obj1 = I;
Object obj2 = 'a ';
2. string class
The string class is used to operate strings. It is the alias of the pre-defined class System. String.
String str1 = "mikecat ";
You can use "+" to connect two strings.
String str2 = "username:" + "mikecat ";
To access a single character, use a subscript.
Char c = str1 [0];
Compares two strings to see if they are equal. The available comparison operator "=" // is different from the basic syntax.
Bool B = (str1 = str2 );

In c #, the most flexible and hard-to-Master pointer in c and c ++ is removed. In c #, how does one provide function pointers in c/c ++? C # provides a delegate, which is a reference type inherited from the System. Delegate class. It is equivalent to the function pointer prototype. Unlike function pointers, delegate is type-safe in c #, and delegate is especially suitable for anonymous calls. To use a delegate, three steps are required: Declaration, instantiation, and call.
Using System;
// Declare a delegate named mfDelegate, which has a string-type parameter
// C # A new class will be generated during compiler compilation. This class inherits from System. Delegate, Class
// Name mfDelegate
Public delegate void mfDelegate (string name );

Public class MikeCat
{
// Define the method Hello () that has the same parameter type as mfDelegate ()
Public static void Hello (string name)
{
Console. WriteLine ("Hello, {0 }! ", Name );
}
// Define the GoodBye () method with the same parameter type as mfDelegate ()
Public static void GoodBye (string name)
{
Console. WriteLine ("Goodbye, {0 }! ", Name );
}
Public static void Main ()
{
// Create an mfDelegate instance mf1
MfDelegate mf1 = new mfDelegate (Hello );
// Call mf1
Mf1 ("mikecat ");
MfDelegate mf2 = new mfDelegate (GoodBye );
Mf2 ("mikecat ");
// Combine mf1 mf2 into a new delegated mf3
MfDelegate mf3 = mf1 + mf2;
// Call mf3
Mf3 ("Mike ");
// Delete mf1 from the composite delegate mf3
MfDelegate mf4 = mf3-mf1;
Mf4 ("mikecat ");
}
}
Program result: Hello, mikecat! // Mf1; goodbye, mikecat! // Mf2
Hello, Mike! Goodbye, Mike! // Mf3
Goodbye, mikecat! // Mf4

This time we will first explain the type conversion. We often use type conversion when writing programs, and there are many rules. I will give a rough explanation here.
Implicit conversions are the default conversions that can be performed without declaration.
1. Implicit numeric Conversion
Implicit numeric conversion is actually a conversion from low-precision numeric type to high-precision numeric type.
Byte x = 255; ushort y = x; y = 65535; float z = y; // both from low precision to high precision. Otherwise, overflow occurs.
There are too many types of implicit numeric conversion, so I will not introduce them much. Remember the above principles. For detailed rules, see msdn
2. Implicit Enumeration Conversion
Implicit Enumeration conversion is used to convert a decimal integer 0 to any enumeration type. Other integers do not have this conversion.
Using System;
Enum Color
{
Red, Green, Blue
};
Class MikeCat
{
Static void Main ()
{
Color c; // declare the Color variable c;
C = 0; // convert 0 to Red;
Console. writeLine ("the value of c is {0}", c); // result: the value of c is Red; if c = 0 is changed to c = 1, the compiler will give an error.
}
}
3. implicit reference Conversion
Conversion from any reference type to object.
Conversion from Class A to Class B, where class A is derived from Class B.
The conversion from Class A to interface B, where class A implements interface B.
The conversion from interface type A to interface type B, where interface A is derived from interface B.
Conversion from any Array type to System. Array.
The conversion from any Delegate type to System. Delegate.
Conversion from any array type or delegate type to System. ICloneable.
Convert from null to any reference type.
A display conversion is also called a forced conversion. You must specify the Conversion Type explicitly.
Char c = (char) 65; //
Int I = (int) 'A'; // 65
Display conversions include all implicit conversions, that is, any implicit conversions allowed by the system are allowed in the form of display conversions.
Int I = 300;
Long l = (long) I;
Another example:
Using System;
Class MikeCat
{
Static void Main ()
{
Long longValue = Int64.MaxValue;
Int intValue = (int) longValue;
Console. WriteLine ("(int) {0 }={ 1}", longValue, intValue );
}
}
Type long to int is an explicit conversion, which uses a forced conversion expression. Output:
(Int) 9223372036854775807 =-1 This is because of overflow.
1. Display numeric Conversion
Display numeric conversion refers to converting from one numeric type to another when there is no corresponding implicit conversion. The conversion type is also cumbersome. You only need to remember the conversion rules and refer to MSDN for details. Because the displayed value conversion may lose information or cause exceptions, the conversion is handled in the following principle: OverFlowException is caused when the high-precision display is converted to a low-precision display ), if no exception is thrown, the value of the source variable is rounded to the nearest integer value as the conversion result. For details about the exception during conversion, refer to MSDN
/* Test. cs */
Using System;
Public class MikeCat
{
Public static void Main ()
{
Ushort u= 65535;
Byte B = (byte) u;
Console. WriteLine ("the value of B is {0}", B );
}

}
The compilation status is as follows:
E: "> csc test. cs
Microsoft (R) Visual C #. NET compiler version 7.10.3052.4
Used for Microsoft (R). NET Framework Version 1.1.4322
Copyright (C) Microsoft Corporation 2001-2002. All rights reserved.
E: "> test.exe
The value of B is 255
E: "> csc/checked test. cs // checked [+ |-] generates an overflow check.
E: "> test.exe
Unprocessed exception: System. OverflowException: overflow caused by arithmetic operations.
At MikeCat. Main ()
E: "> csc/checked-test. cs
E: "> test.exe
The value of B is 255
2. Display enumeration Conversion
Display enumeration conversion is to implicitly display and convert the Element Types of enumeration types and corresponding types. For example, if you want to convert an int-type Enumeration type E from E to byte, you can convert the display value from int to byte.
Using System;
Enum Color
{
Red, Green, Blue
};
Public class MikeCat
{
Static void Main ()
{
Color c; // declare the Color variable c;
C = (Color) 4; // display the number 3 for enumeration Conversion
Console. WriteLine ("the value of c is {0}", c );
}
}
Result: The value of c is 4.
Convert class
Converts a basic data type to another basic data type.
The return value of this class is equivalent to the value of the specified type. Supported base types are Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime, and String.

There is a conversion method to convert each base type to each other base type. However, the actual conversion operations are divided into three types:

The conversion from a type to itself only returns this type. No conversion is actually performed.
An InvalidCastException is thrown when a conversion fails to produce meaningful results. No conversion is actually performed. The following conversions cause an exception: Convert from Char to Boolean, Single, Double, Decimal or DateTime, and convert from these types to Char. The following conversion causes an exception: Converting from DateTime to any type other than String and from any type (except String) to DateTime.
Any base type (except the base type described above) can be converted to any other base type.
If the number type conversion results in loss of precision (that is, the loss of some minimum valid bits), no exception is thrown. However, if the result is out of the range that can be expressed by the return value type of a specific conversion method, an exception is thrown.

The following describes the packing and unboxing related to type conversion.
Packing is an implicit conversion of the value type to the object type or to any interface type implemented by this value type. Binning a value will allocate an object instance and copy the value to the new object.

See the Declaration of the following value type variables:

Int I = 123;
The following statement implicitly applies the packing operation to variable I:

Object o = I;
The result of this statement is to create the object o on the stack, and the object references the int type value on the stack. This value is a copy of the Value Type value assigned to variable I. The differences between the two variables I and o are described.

Packing and conversion
Stack on Stack
I 123
Int I = 123;
O (packing I)
Object o = I; int 123
You can also explicitly perform the packing as shown in the following example (but not necessary:
Int I = 123;
Object o = (object) I;
Example
In this example, the integer variable I is converted to the object o through packing. In this way, the value stored in variable I is changed from 123 to 456. In this example, the object retains the original copy of the content, that is, 123.
// Boxing. cs
// Boxing an integer variable
Using System;
Class TestBoxing
{
Public static void Main ()
{
Int I = 123;
Object o = I; // Implicit boxing
I = 456; // Change the contents of I
Console. WriteLine ("The value-type value = {0}", I );
Console. WriteLine ("The object-type value = {0}", o );
}
}
Output
The value-type value = 456
The object-type value = 123

Unboxing
Unboxing is an explicit conversion from the object type to the value type or from the interface type to the value type that implements this interface. Unboxing includes:

Check the object instance to make sure it is a boxed value of the given value type.
Copy the value from the instance to the value type variable.
The following statements describe both packing and unboxing:

Int I = 123; // A value type
Object box = I; // Boxing
Int j = (int) box; // Unboxing
The result of the preceding statement is displayed.

Cancel packing Conversion
Stack on Stack
I 123
Int I = 123;
O (packing I)
Object o = I; int 123
J 123
Int j = (int) o;
To make the unboxing conversion of the given value type successful at runtime, the source parameter value must be a reference to an object, this object was previously created by packing the value of this value type. If the source parameter is null or a reference to an incompatible object, InvalidCastException is thrown.
Example
The following example illustrates how InvalidCastException is caused by incorrect unboxing. By using try and catch, an error message is displayed when an error occurs.
Using System;
Public class UnboxingTest
{
Public static void Main ()
{
Int inti= 123;
// Boxing
Object o = intI;
// Reference to incompatible object produces InvalidCastException
Try
{
Int intJ = (short) o;
Console. WriteLine ("Unboxing OK .");
}
Catch (InvalidCastException e)
{
Console. WriteLine ("{0} Error: Incorrect unboxing.", e );
}
}
}
Output
System. InvalidCastException
At UnboxingTest. Main () Error: Incorrect unboxing.
If the following statements are used:
Int intJ = (short) o;
Changed:
Int intJ = (int) o;
The conversion will be executed, and you will get the output "Unboxing OK ".

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.