Learning C # (1)

Source: Internet
Author: User
Tags to domain
Document directory
  • Data Type
  • Variables and constants
  • Operators and expressions
  • Namespaces and statements

Http://www.microsoft.com/china/msdn/library/langtool/vcsharp/cornyfield.mspx reading

C # Sharp experience Release Date: 2/4/2002 | updated on: 6/22/2004

Li Jianzhong (jzli@china.com), Nanjing University of Posts and Telecommunications)

Note:

Lecture 1 "Hello, world !" Program

// Helloworld. cs by cornfield, 2001 // CSC helloworld. csusing system; Class helloworld {public static void main () {console. writeline ("Hello world! ") ;}} C # supports two annotation Methods: single line annotation starting with" // "and multiple lines used in"/* "," */"pairing
Annotations. Annotations cannot be nested.
I think there should be a third type of // for generating documents, similar to Java
About using statements:
Of course, the using indicator is not required. We can use the global name of the type to obtain the type. Actual
The Using statement does not have any impact on the C # compilation and output program.
The namespace type reference method is extended.

C # Use namespace to organize programs. Namespaces can be nested. Using indicator

It can be used to simplify the reference of the namespace type. Using indicators can be used in two ways.

"Using system;" statements allow us to replace the type with a short type name "console"

"System. Console ".

"Using output = system. Console;" The statement allows us to use the alias "output"

The replacement type is "system. Console ". The introduction of namespaces greatly simplifies the organization of C # programs.

 

We declare and implement a helloworld class containing the static main () function. C # All sounds

And implementations must be placed in the same file. Unlike C ++, the two can be separated. Main () function

It is very special in C #. It is the entry point for all executable programs specified by the compiler. Due to its particularity,

We have the following guidelines for the main () function:

1.

The main () function must be encapsulated in a class or structure to provide the entry point of the executable program. C # adopts a completely object-oriented programming method. In C #, global functions such as C ++ cannot be used.

2.

The main () function must be a static function ). This allows C # To run programs without creating instance objects.

3.

There are no special requirements for the protection level of the main () function. Public, protected, private, and so on can all be used, but we usually specify it as public. (Note: Of course, the first public line cannot be capitalized)

4.

The first letter of the main () function name should be capitalized (Note: different from Java), otherwise it will not have the semantics of the entry point. C # is a case-sensitive language.

5.

The main () function has only two parameters: the command line parameters without parameters and the string array, that is, static void main () or static void main (string [] ARGs ), the latter accepts command line parameters. A c # program can have only one main () function entry point. Parameters of other forms do not have entry point semantics. C # does not recommend that you use other parameters to overload the main () function, which causes compilation warnings.

6.

The Return Value of the main () function can only be void (no type) or int (integer type ). Other forms of return values do not have entry point semantics.

Compiled and output helloworld.exe is a metadata) and an additional standard executable file header of the target PLATFORM added by the compiler (for example, the Win32 platform adds a standard Win32 executable file header) (portable executable, but not traditional binary executable files-although they have the same extension. An intermediate language is a set of CPU-independent instruction sets that can be translated by the instant compiler jitter into local code on the target platform. The intermediate language code makes the C #, VB. NET, and VC. NET languages of all Microsoft. NET platforms independent of each other and implement interoperability between languages. Metadata is a collection of tables embedded in PE files. Metadata describes the data types in the Code and other information that must be known during code execution in the common language runtime. Metadata enables the. NET application code to have a custom description feature and provides type security assurance. In the past, an additional type library or Interface Definition Language (IDL) was required ).

Run the "ildasm/output: helloworld. Il helloworld.exe" command to obtain two output files: helloworld. Il and helloworld. Res. The latter is the extracted resource file for the moment. Let's look at the helloworld. Il file.

Similar to the earlier assembly language, but it has the object definition and operation functions. We can see that it defines and implements a helloworld class inherited from system. Object and two functions: Main () and. ctor ().

Lecture C # basic introduction to Data Types

C # language data types are mainly divided into two types: Value Type and reference type. Another data type "Pointer" is specially set for the unsafe context programming, among them, the unsafe context refers to the C # unmanaged code that identifies the code to meet the requirements for Direct Memory operations using pointers. These codes will lose Microsoft.. NET platform spam and other CLR Properties

Null indicates that the reference type does not reference any actual address.

Value types can be divided into structure type and enumeration type. The structure types include simple and custom structure types. Simple types can be classified into boolean and numerical types. In C #, The boolean type is strictly distinguished from the numeric type. There are only true and false values, and there is no conversion between the Boolean Type and other types like in C/C ++. Value types include integer, floating point, and decimal. There are nine types of integer values: sbyte, byte, short, ushort, Int, uint, long, ulong, and char. Except for the char type, there are two groups of the other eight types: signed and unsigned. Floating point values include float and double. Decimal is mainly used in financial, currency, and other computing environments with high precision requirements. The following table provides a detailed description of these simple types:

Simple Type Description Example

Sbyte

8-bit signed integer

Sbyte val = 12;

Short

16-bit signed integer

Short val = 12;

Int

32-bit signed integer

Int val = 12;

Long

64-bit signed integer

Long val1 = 12; long val2 = 34l;

Byte

8-bit unsigned integer

Byte val1 = 12; byte val2 = 34u;

Ushort

16-bit unsigned integer

Ushort val1 = 12; ushort val2 = 34u;

Uint

32-bit unsigned integer

Uint val1 = 12; uint val2 = 34u;

Ulong

64-bit unsigned integer

Ulong val1 = 12; ulong val2 = 34u; ulong val3 = 56l; ulong val4 = 78ul;

Float

32-Bit Single-precision floating point number

Float val = 1.23f;

Double

64-bit double-precision floating point number

Double val1 = 1.23; double val2 = 4.56d;

Bool

Boolean Type

Bool val1 = true; bool val2 = false;

Char

Character type, Unicode encoding

Char val = 'H ';

Decimal

128-bit decimal type of 28 valid digits

Decimal val = 1.23 m;

There are four types of reference: Class, interface, array, and delegate. In addition to defining our own types, the class also includes two special types of object and string. Object is the inherited root class of all types (including all value types and reference types) in C. The string type is a sealed type (which cannot be inherited), and its instance represents a unicode string. It and the array type are described in "9th lecture structure, enumeration, array and string. The contract for defining a method for an interface type is described in Section 7 interface inheritance and polymorphism. The delegate type is a signature pointing to a static or instance method. It is similar to the function pointer in C/C ++ and will be described in "lecture 8 delegate and event. In fact, we will see from the topics below that these types are packaged in some form of classes.

Each data type has a corresponding default value. The default value of the numeric type is 0 or 0.0, and the default value of char is '/x000000 '. The default value of boolean type is false. The default value of Enumeration type is 0. The default value of the structure type is to set all its value type fields to the default value of the corresponding value type, and set its reference type fields to null. The default value of all reference types is null.

Data of different types can be converted. There are four types of conversion in C #: implicit conversion, clear conversion, standard conversion, and custom conversion. Implicit conversion is the same as explicit conversion in C ++. Data is implicitly converted from "Small Type" to "large type, the conversion from "big type" to "Small Type" is clear conversion, and clear conversion needs to be a bracket conversion operator such as "(type) data. Standard conversion and custom conversion are both for Built-in System Conversion and user-defined conversion. Both are for custom types such as classes or structures.

Variables and constants

A variable indicates the storage location. A variable must have a certain data type. One of the meanings of C #'s type security is to ensure that the storage location of the variable contains the appropriate type. The variables in C # can be divided into seven types: static variables, instance variables, value passing parameters, reference parameters, output parameters, array parameters, and local variables. Local variables are temporary variables in the method body.

Static variables and instance variables are mainly for data members (also called domains) in a class or structure. Static variables get the bucket after the class or structure type it stores is loaded. If it is not initialized and assigned a value, the initial value of the static variable will be the default value held by its type. The instance variable obtains the bucket after its class instance is created. If it is not initialized and assigned a value, its initial value is the same as the definition of the static variable. The two are described in more detail in the topic "section 6 domain method attributes and indexer.

The input parameter, reference parameter, output parameter, and array parameter are mainly for the parameter type of the method. In short, the pass-through parameter is a transfer of the value of the variable, and the change of the variable in the method does not take effect in the method in vitro. The variables that are referenced by the value passing parameter are slightly different. The changes in the actual memory block pointed to by the referenced (handle) variable in the method will remain unchanged in the method, however, changes to the reference (handle) itself do not work. A reference parameter is a transfer of the variable handle. Any changes made to the variable in the method will be retained in the method. The output parameter is C # tailored specifically for methods with multiple return values. It is similar to referencing variables, but can not be initialized before entering the method body, other parameters require Explicit initialization when entering method C. Array parameters are specially designed to pass a large number of array elements. They are essentially a value passing parameter for referenced variables. They are also described in more detail in the topic "Introduction to domain method attributes and indexer.

Local variables are strictly stated in block statements of C #, for statements, switch statements, and using statements. their lifecycles are strictly restricted within these statement blocks.

The value of a constant is determined during compilation and cannot be modified throughout the program. A value must be assigned when a constant is declared. Due to its feature of determining the value during compilation, the possible values of the reference type can only be string and null (except string, the reference type builder must be at runtime to determine the value of the reference type ).

Operators and expressions

C # retains all operators in C ++. the pointer operator (* and->) and the reference operator (&) need to have an unsafe context. C # If the range discrimination operator (: :) is removed, all operators are changed to single-point operators (.). We will not elaborate on the reserved C ++ operators. Here we will mainly introduce some special operators introduced by C #: As, is, new, typeof, sizeof, and stackalloc.

The as operator is used to convert compatible types. When the conversion fails, the as operator returns NULL. The is operator is used to check whether the runtime type of the object is compatible with the given type. When the expression is not null and can be converted to the specified type, the is Operator returns true; otherwise, it returns false. The AS and is operators are designed based on the same type identification and conversion. They have similar applications. In fact, expression as type is equivalent to expression is type? (Type) expression: (type) null.

(Which of the following variables are placed on the heap and stack respectively)

The new operator is used to create objects on the stack and call constructors. It is worth noting that value-type objects (such as structures) are created on the stack, and reference type objects (such as classes) is created on the stack. New is also used as a modifier to hide the inherited members of a base class member. To hide inherited members, declare the member in the derived class with the same name and modify it with the new modifier. The typeof operator is used to obtain a certain type of system. Type object. We will describe it in detail by combining the Microsoft. NET Type System in "feature and ing. The sizeof operator is used to obtain the size (in bytes) of the value type (not applicable to reference types ). Stackalloc is used to allocate memory blocks on the stack. It is only valid in the initial values of local variables, similar to _ alloca in C/C ++. Both sizeof and statckalloc require the unsafe context because of Direct Memory operations.

Some operators in C # Can be overloaded as in C ++. Operator Overloading allows a user-defined type (class or structure) to easily express some common operations with simple operators.

The combination of a series of operators and operands that complete a calculation result is called an expression. Like C ++, C # expressions can be divided into value assignment expressions and boolean expressions. C # does not introduce new expressions, so we will not repeat them here.

Namespaces and statements

C # Use namespace to organize programs. Namespaces can be nested.

C # statements can be divided into label statements, declaration statements, block statements, empty statements, expression statements, select statements, repeated statements, jump statements, try statements, checked/unchecked statements, and lock statements, using statement.

The label statement is mainly designed for goto jump. C # does not allow cross-method jump, but allows small-scale jump within the method. The declaration statement can be initialized and assigned values at the same time. The Object Instantiation Declaration requires the new keyword. Block statements use "{" and "}" to define block statements, mainly to define the scope of local variables. The empty statement is represented by a semicolon (;) in C #, and no execution semantics is executed. Expression statements use expressions to form statements.

The SELECT statement can be an if statement or a switch statement, which is similar to C ++. In addition to the while, do, and for loop structures, the foreach statement is introduced to traverse all elements in the set. However, this requires the support of specific interfaces, we will elaborate on this in later chapters.

The jump statements include the break, continue, Goto, return, and throw statements. The first four statements have the same semantics as those in C ++, the throw statement and the subsequent try statement will be described in "11th about com interoperability unmanaged programming and Exception Handling.

The checked/unchecked statement is mainly used for the context of overflow check in numerical operations. The lock statement is mainly used for Lock control of thread semaphores. Using statements are mainly used for fragment resource management. These will be detailed in subsequent chapters.

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.