MSDN C # tutorial

xiaoxiao2021-03-06  46

Array Tutorial: When declares an array, square brackets ([]) must follow the type instead of the identifier. In C #, the square bracket is placed after the identifier is a syntax. Int [] table; // not int reference is that the size of the array is not part of its type, and it is part of the array type in the C language. This allows you to declare an array and assign any array of int objects, regardless of the length of array. Int [] NumBers; // Declare NumBers as an int Array of any sizenumbers = new int [10]; // NumBers is a 10-element arrayNumBers = new int [20]; // NOW it's a 20-element array

One-dimensional array: int [] NumBers; multi-dimensional array: string [,] name; array array (interleaved): Byte [] [] score; declaration array (as shown above) does not actually create them. In C #, the array is an object (discussed later), it must be instantiated. The following example shows how to create an array: one-dimensional array: int [] NumBers = new int [5]; multidimensional array: string [,] names = new string [5,4]; array of arrays (interlaced): byte [ ] [] score = new byte [5] []; for (int x = 0; x

You can use the Foreach statement to traverse the array.

Attribute tutorial:

PUBLIC STRING NAME · {· Get ​​· {· Return MyName; ·} · set · {· myname = value; ·} ·}

Visual C # Language Concepts You can call the C # compiler on the command line by typing the C # compiler on the command line on the command line. If you want to call CSC.exe from any subdirectories on your computer, you may need to adjust the path. This topic provides more information about the following: • Run the difference between the Vcvars32.bat · C # compiler and C compiler output · Command line syntax rules · Command line example runs vcvars32.batvcvars32.bat Set the appropriate environment variable to enable Command line compilation. Run vcvars32.bat 1. Change to the installed / bin subdirectory installed at the command prompt. 2. Run vcvars32.bat by typing VCVARS32. WARNING VCVARS32.BAT varies depending on the computer. Do not replace the lost or damaged vcvars32.bat file with vcvars32.bat on other computers. Run the installer to replace the lost file. For more information on vcvars32.bat, see the Knowledge Base article below: • Q248802: vcvars32.bat generates out of environment message If the Visual Studio current version is installed on a computer already have Visual Studio, it should not be in the same Run from different versions of Vcvars32.bat in the command window. The difference between the C # compiler and the C compiler output is the result of calling the C # compiler without creating any object (.Obj) file; creating the output file directly. Therefore, the C # compiler does not require a linker. The command line syntax rules When explaining the parameters given on the operating system command line, the C # compiler code uses the following rules: • The parameter is separated by blank, blank can be a space or a tab. • ^ Character (^) is not identified as an escap or separator. This character is completely processed by the command line analyzer of the operating system before being passed to the Argv array of the program. · No matter how blank is there, the strings included in the double quotes ("string") are interpreted as a single parameter. Strings with quotation marks can be embedded in parameters. · Double quotation marks (/ ") in front of the front, is interpreted as the primary double quotes character ("). · The backslash is explained by its original, unless they are tight before double quotes. • If an even aversion is followed by double quotes, a backslash in each pair of backslash is placed in an argv array, and the dual quotes are interpreted as a string separator. • If the odd substrate is followed by double quotes, each pair of backslaps in the backslash is placed in the argv array, and the double quotes are "escape" by the rest of the backslash, so that the original double quotes (") Placed in the Argv array. Command line example · Compile file.cs to generate file.exe: CSC file.cs · Compile File.cs to generate file.dll: CSC / Target: library file.cs · Compile file.cs Create MY.EXE: CSC /out :my.exe file.cs · By using optimized and definition debug symbols, compile all C # files in the current directory. Output is file2.exe: CSC / Define: debug / Optimize / Out: File2 .exe * .cs • Compile all C # files in the current directory to generate file2.dll debug versions.

No logo and warning: CSC / target: library /out:file2.dll / warn: 0 / noogo / debug * .cs • Compile all the C # files in the current directory to Something.xyz (a DLL): CSC / Target: library /out:something.xyz * .s Mr. Mirase is a DLL module, and then call it in the main program, pay attention to the DLL file must be in the same folder.

The version control tutorial is in C #, the method is not virtual by default. To make the method become a virtual method, you must use the Virtual modifier in the basic class method declaration. Then, the derived class can use the Override keyword rewrite the base virtual method, or use the NEW keyword hide the virtual method in the base class. If the Override keyword and the NEW keyword are not specified, the compiler will issue a warning and the method in the derived class will hide the method in the base class.

Note: The NEW keyword and the Override keyword get the reverse result, the default is the new method.

The collection class tutorial The Foreach statement is a convenient way to loop access array elements. If the set class has implemented System.Collections.ieNumerator and System.Collections.ienumerable interface, it can also enumerate the elements of the collection. In C #, the collection class is not necessary to inherit from IEnumerable and IEnumerator to compatibility with Foreach; as long as the class has the required GetENUMERATOR, MOVENEXT, RESET, and CURRENT members can be used with Foreach. The benefits of the omission of the interface are for you to define the return type of the Current to be more clear than Object, so that type security is provided.

The following code example explains how to write a collection class that can be used with Foreach. This class is a string tagged splitter, similar to the C runtime library function start STRTOK. // tokens.csusing system; // the system.collections namespace is master available: using system.collections;

// Declare the tokens class: public class tokens: ienumerable {private string [] Elements;

Tokens (String Source, Char [] Delimiters) {// Parse The String Into Tokens: Elements = Source.Split (Delimiters);

// {{{{{r r r};};}

// Inner Class Implements IENUMERATOR Interface: Private Class TokenUmerator: IENUMERATOR {Private INT POSITION = -1; Private Tokens T;

Public tokenenumerator (tokens t) {this.t = t;}

// Declare the MoveNext method required by IEnumerator: public bool MoveNext () {if (position

// Declare the current property request by ienumerator: public object current {get {return t.elements [position];}}}

// Test tokens, tokenenumerator

Static void main () {// Testing tokens by breaking the string in tokens: tokens f = new tokens ("this is a well-done program", new char [] {'', '-'}); Foreach String item in f) {console.writeLine (item);}}} The structural tutorial structure may seem like a class, but there are some important differences and should be paid attention to. First, the class is a reference type, and the structure is a value type. Using the structure, you can create a behavior similar to a built-in type, while enjoying their benefits.

Stack or stack? When you call the New (New) operator on the class, it will allocate on the heap. However, when instantiated, the structure will be created on the stack. This will result in performance gain. Moreover, you will not process references to structure instances like treating them. You will do it directly to the structural instance. In view of this reason, the structure is transmitted to the method, and the structure will pass values, not as reference delivery.

The structure can declare the constructor, but they must have parameters. The default (non-parameter) constructor of the declaration structure is wrong. Structural members cannot have initial value settings. Always provide default constructor to initialize structural members to their default values. When you create a structural object with a New operator, the structure object is created and the appropriate constructor is called. Different from the class, instantiation of the structure may not use the New operator. If you do not use New (New), the field will remain unfaised before initializing all fields, and the object is not available. For structures, there is no inheritance like classes. A structure cannot inherit from another structure or class, and cannot be used as a class of a class. However, the structure is inherited from the base class object. The structure can implement the interface, and the implementation is exactly the same as the class implementation interface.

The structure is simple and sometimes it is useful. But keep in mind: The structure is created in the stack, and you are not a reference to the structure, but the direct processing structure. Whenever a type that will be used frequently, and most cases this type is just some data, the structure may be the best choice.

Indexer Tutorial Definition "Indexer" allows you to create classes as the "virtual array". An instance of such a class can be accessed using the [] array access operator. Define the indefinometers in the C # similar to the definition operator in C [], but the former is much flexible. For classes that encapsulate functions of similar arrays or similar characters, use the indexer to enable the user to access the class using the array syntax. Example This example, the FileByTearRay class makes it possible to access the file like byte arrays. The byte of the Reverse class reversal file. You can run the program to reverse the byte of any text file, including the program source file itself. To change the reversible file back to the normal state, run the program again on the same file. // Indexer.cs // arguments: indexer.txtusing system; using system.io;

// Class to provide access to a large file // as if it were a byte array.public class FileByteArray {Stream stream; // Holds the underlying stream // used to access the file.// Create a new FileByteArray encapsulating a particular File (String FileName) {stream = new filestream (filename, filemode.open);

// Close The Stream. This SHOULD BE The Last Thing Done // WHEN YOUSE () {stream.close (); stream = null;

// Indexer to Provide Read / Write Access To the File. Public Byte this [long index] // long IS A 64-bit integer {// read one byte at offset index and return it. Get {byte [] buffer = new Byte [1]; stream.seek (index, seekorigin.begin); stream.read (buffer, 0, 1); return buffer [0];} // Write One byte at offset index and return it. set {byte [ ] buffer = new byte [1] {value}; stream.seek (index, seekorigin.begin); stream.write (buffer, 0, 1);}}

// Get the total length of the file. Public long length {get {return stream.seek (0, seekorigin.end);}}}

// Demonstrate the FileByteArray class.// Reverses the bytes in a file.public class Reverse {public static void Main (String [] args) {// Check for arguments. If (args.Length == 0) {Console.WriteLine ("Indexer "); returnTearray File = New FileByteArray (args [0]); long len = file.length;

// swap bytes in the file to reverse it. For (long i = 0; i

// Note That indexing the "file" Variable Invokes the // Indexer on the filebytestream class, which reads // and writes the bytes in the file. T = file [i]; file [i] = file [len - i - 1]; File [LEN - I - 1] = T;}

File.close ();}} Enter: Indexer.txt To test programs, text files with the following are called Test.txt in the "Indexer" example). Public class hello1 {public static void main () {system.console.writeline ("Hello, World!");}} To reverse the byte of the file, compile the program, then use the following command line: Indexer Indexer .txt To display the reverse file, enter the command: type indexer.txt sample output}}; "! dlrow, Olleh" (Niam Diov Citats Cilbup {1 OLLH SSALC CILBUP user-defined Conversion Tutorial C # Allows programmers to declare conversion on classes or structures to enable classes or structures to transform each other or structural or basic types. The definition method of conversion is similar to the operator, and naming it according to the types they convert In C #, you can declare the conversion declaration as an Implicit (automatic conversion when needed) or explicit (need to call the conversion). All conversion must be Static, and must be used to define the type thereof, or return this type. Example 2 This example defines two structures of RomanNumeral, and demonstrates both between the two. // structconversion.csusing system;

struct RomanNumeral {public RomanNumeral (int value) {this.value = value;} static public implicit operator RomanNumeral (int value) {return new RomanNumeral (value);} static public implicit operator RomanNumeral (BinaryNumeral binary) {return new RomanNumeral (( int) binary);} static public explicit operator int (RomanNumeral roman) {return roman.value;} static public implicit operator string (RomanNumeral roman) {return ( "Conversion not yet implemented");} private int value;} struct BinaryNumeral {public BinaryNumeral (int value) {this.value = value;} static public implicit operator BinaryNumeral (int value) {return new BinaryNumeral (value);} static public implicit operator string (BinaryNumeral binary) {return ( "Conversion not yet implemented ");} Static public explicit operator int (binarynumeral binary) {return (binary.value);

PRIVATE INT VALUE;

Class test {static public void main () {RomanNumeral Roman; Roman = 10; binarynumeral binary; // perform a converarsion from a romanNumeral to a // binarynumeral: binary = (binarynumen) (int)) Roman; // performs a conversion from a binarynumeral to a romannumeral. // no cast is required: roman = binary; console.writeline ((int) binary); console.writeline (binary);}} Output 10conversion Not Yet Implement

Operator Overload Tutorial Example 1 This example shows how to use an operator overload to create a complex COMPLEX that defines a plural addition. This program uses the overload of the TOString method to display the virtual partial and real part of the number and the result of the addition. // Complex.csusing system;

Public struct complex {public int real; public int int

Public complex (int real, int imaginary) {this.real = real; this.imaginary = imaginary;} // Declare Which Operator To overload ( ), That Can Be Added (Two Complex Objects), and the // Return Type (Complex): Public Static Complex Operator (Complex C1, Complex C2) {Return New Complex (C1.Real C2.Real, C1.Imaginary C2.Imaginary);} // Override the Tostring Method To Display An Complex Number in The Suitable Format: Public Override String Tostring () {Return ("{0} {1} i", real, imaginary);}

Public static void main () {complex num1 = new complex (2, 3); Complex Num2 = New Complex (3, 4);

// Add Two complex Objects (Num1 and Num2) THROUGH THE // Overloaded Plus Operator: complex sum = Num1 Num2;

// Print The Numbers and The Sum Using The Overriden Tostring Method: Console.Writeline ("First Complex Number: {0}", Num1); Console.Writeline ("Second Complex Number: {0}", Num2); console. WriteLine ("The Sum of The Two Numbers: {0}", SUM);}} Output First Complex Number: 2 3isecond Complex Number: 3 4In Sum of The Two NumBers: 5 7i

Principal Tutorial · Declaration Entrust the following statement: Public Delegate Void ProcessBookDelegate (Book Book); Declare a new entrustment type. Each delegate type describes the number and type of parameters, and the return value type of how it can be packaged. Whenever a set of new parameter types or new return value types must be declared, a new entrustment type must be declared. · Instantiate the entrustment statement After the entrustment type must create a delegate object and associate with a particular method. Similar to all other objects, the new delegate object is created with New Expressions. But when you create a delegate, the parameters pass to the New Expression are very special: its writing is similar to the method call, but there is no method for parameters. The following statement: BookDb.ProcessPaperBackBookBooks (New ProcessBookDelegate (PrintTitle); create a new delegation object associated with the static method Test.printTitle. The following statement: BookDb.ProcessPaperbackBookBooks (New ProcessBookDelegate (Totaller.Addbooktota); Create a new delegate object associated with the non-static method AddbookTotota on Totaller. In two examples, the new delegate object is immediately passed to the ProcessPaperBackBooks method. Note Once the delegate is created, the method it associated will never change: the delegate object cannot be changed. · After the debused creation of the delegate object, the delegate object is usually passed to other code that will call the delegate. Call the entrustment object by the name of the delegate object (behind follow the parameters to be transmitted to the entrusted). The following is an example of a delegated call: ProcessBook (b); delegated - routine // compose.csusing system; delegate void mydelegate (String s);

Class myclass {public static void hello (string s) {console.writeline ("Hello, {0}!", s);

Public static void goodbye (string s) {console.writeline ("Goodbye, {0}!", s);

Public static void main () {MyDelegate A, B, C, D;

// Create the delegate object a that references // the method Hello: a = new MyDelegate (Hello); // Create the delegate object b that references // the method Goodbye: b = new MyDelegate (Goodbye); // The two Delegates, A and B, Are Composed to form c: c = a b; // remove a from the composed delegate, Leaving D, // Which calls only the method goodbye: d = c - a;

Console.writeline ("Invoking Delegate A:"); A ("a"); "INVOKING DELEGATE B:"); B ("B"); console.writeline ("Invoking Delegate C:"); C ("c"); "INVOKING DELEGATE D:"); D ("D");}}}} Output Invoking Delegate A: Hello, A! Invoking Delegate B: Goodbye, B! Invoking Delegate C: Hello , C! Goodbye, c! Invoking delegate D: Goodbye, D! Event tutorial

· Statement incidents to declare events within the category, first must declare the delegate type (if there is no declaration). Public Delegate Void ChangeDeventHandler (Object Sender, Eventargs E); a set of parameters that pass to the method of processing the event. Multiple events can share the same delegate type, so this step is only required when any suitable commission type has not yet been declared. Next, declare the event itself. Public Event ChangeDeventHandler Changed; Declare the event is similar to the field of the declaration, just the keyword Event, in front of the event declaration, behind the modifier. Events are usually declared as public events, but allow any access to modifiers. • Calling the event class declares that the event can be processed as if you deal with the fields of delegated types. If no client will entrust with the event, this field will be empty; otherwise the field reference should be invoked when calling the event. Therefore, when you call an event, you will usually check if it is empty, then call the event. • if (Changed! = NULL) Changed (this, e); calling events can only be done within the class that declares the event. · Hook with event hooks from the category of statement, events are like a field, but access to this field is very limited. You can only perform the following: • Write a new delegate on this field. · Remove the delegate from the field (probably a compound field). Use the = and - = operator to complete this. To start receiving event calls, customer code first creates a delegate of event types, which should be called from event calls. Then it uses = to write the delegate to any other delegation that may be connected. // Add "listchanged" to the change Event on "list": list.changed = new changeEventHandler (ListChanged); After the customer code completes the receiving event call, it will use the operator - = from the event to the delegate. // DETACH The Event and delete the list: list.changed - = new changedEventHandler (ListChanged);

.NET Framework Guide Although the C # language allows events to use any delegate type, ".NET Framework" has some stricter guidelines for the delegate types that should be used. If you plan to use your components with ".NET Framework", you may want to follow these guidelines. The ".NET Framework" guide indicates that the delegate type for the event should be used in two parameters: "E" parameters of the "Object Source" parameter of the event source and the other related information of the package event. The type of "e" parameter should be derived from the Eventargs class. For events that do not use any other information, ". Net Framework" has defined an appropriate entrustment type: EventHandler. Explicit interface implementation tutorial

The class that implements the interface can explicitly implement the member of the interface. When a member is explicitly implemented, the member cannot be accessed by a class instance, and the member can only be accessed by an instance of the interface.

Example 1 This example declares an IDimensions interface and a Box class that explicitly implements interface members Length and Width. Access these members via interface instance MyDimensions. // Explicit1.csinterface idimensions {float length (); float width ();

Class box: idimensions {float lengthinches; float widthinches;

public Box (float length, float width) {lengthInches = length; widthInches = width;} // Explicit interface member implementation: float IDimensions.Length () {return lengthInches;} // Explicit interface member implementation: float IDimensions.Width () {Return WidthInches;

Public static void main () {// declare a class instance "mybox": box mybox = new box (30.0f, 20.0f); // Declare an interface instance "mydimensions": idimensions mydimensions = (idimensions) MyBox; // Print out the dimensions of the box: / * The following commented lines would produce compilation errors because they try to access an explicitly implemented interface member from a class instance: * / //System.Console.WriteLine("Length: {0} " , MyBox.Length ()); //system.console.writeline ("width: {0} ", mybox.width ()); / * Print out the dimensions of the box by calling the methods from an instance of the interface : * / System.console.writeline ("Length: {0}", mydimensions.length ()); System.Console.writeline ("width: {0}", mydimensions.width ());}} Output Length: 30Width: 20 Example 2 Explicit Interface Implementation also allows programmers to inherit two interfaces for sharing the same member name and provide a separate implementation for each interface member. This example also displays the size of the box in the metric unit and the British unit. The Box class inherits the two interfaces of IenglishDimensions and IMEtricDimensions, which represent different degree balance systems. The two interfaces have the same member name Length and Width.

// explicit2.cs // Declare the English units interface: interface IEnglishDimensions {float Length (); float Width ();} // Declare the metric units interface: interface IMetricDimensions {float Length (); float Width ();} / / Declare the "Box" class that implements the two interfaces: // IEnglishDimensions and IMetricDimensions: class Box: IEnglishDimensions, IMetricDimensions {float lengthInches; float widthInches; public Box (float length, float width) {lengthInches = length; widthInches = width; } // Explicitly implement the members of IEnglishDimensions: float IEnglishDimensions.Length () {return lengthInches;} float IEnglishDimensions.Width () {return widthInches;} // Explicitly implement the members of IMetricDimensions: float IMetricDimensions.Length () {return lengthInches * 2.54f;} float imtricdimensions.width () {return widthinches * 2.54f;} public static void main () {// Declare a class i nstance "myBox": Box myBox = new Box (30.0f, 20.0f); // Declare an instance of the English units interface: IEnglishDimensions eDimensions = (IEnglishDimensions) myBox; // Declare an instance of the metric units interface: IMetricDimensions mDimensions = (IMtricDimensions) MyBox; // Print Dimensions in English Units: System.Console.writeline ("Length (in): {0}", Edimensions.Length ()); System.Console.writeline ("Width: {0 }.width ()); // Print Dimensions in Metric Units: System.Console.writeline ("Length (cm): {0}", mdimensions.length (); system.console.writeline Width (cm): {0}, mdimensions.width ());}}

Condition Method Tutorial Document # 2: Use the customer program under the condition method to perform some simple tracing using the TRACE class defined in File # 1. // tracetest.cs // compile with: /Reference: Conment.dll// arguments: a b Cusing system; using tracefunctions

Public class traceclient {public static void main (string [] args) {trace.Message ("main start"); if (args.length == 0) {Console.WriteLine ("no arguments has been passed);} else {For (int i = 0; i

TRACE.MESSAGE ("Main Ending");}} thread processing tutorial

· Creating and executing threads, thread synchronization, thread interaction, using thread pool, using MUTEX objects to protect shared resources

转载请注明原文地址:https://www.9cbs.com/read-59885.html

New Post(0)