C # basics 04,

Source: Internet
Author: User

C # basics 04,

Introduction: Generic introduction, index, Foreach traversal explanation, yield method, path file operations, basic Directory Operations <Directory>

I. Generic

Baidu data: Generic is a new function in the C # language and Common Language Runtime Library (CLR) of version 2.0. Generics introduce the concept of type parameters. NET Framework, type parameters make it possible to design the following classes and Methods: these classes and Methods delay one or more types until the client Code declares and instantiate the class or method. For example, by using the generic type parameter T, you can write a single class that can be used by other client code without introducing the cost or risk of force conversion or packing during runtime,

You can use generic types to maximize code reuse, protect type security, and improve performance. The most common use of generics is to create a collection class .. The. NET Framework class library contains several new Generic collection classes in the System. Collections. Generic namespace. Use these classes as much as possible to replace common classes, such as the ArrayList in the System. Collections namespace. You can create your own generic interfaces, generic classes, generic methods, generic events, and generic delegation. You can restrict generic classes to access specific data types. Information about types used in generic data types can be obtained through reflection at runtime.

* Benefits of generics: code reuse. <T> is used for reuse. Different parameter types can be passed in, or we can define them as generic methods, generic classes, and generic interfaces.

* Custom generic

There are generic classes, generic methods, and generic interfaces.

Eg 1:

/// Custom generic class public class MyClass1 <T> {public void SayHi (T teg) {Console. writeLine (teg) ;}}// generic method public class Myclass2 {public void Say <T> (T er) {Console. writeLine (er) ;}/// generic interface public interface IMyClass3 <T> {T Sayhi (); // return value type void SayHello (T msg ); // parameter type} // two scenarios for implementing a generic interface // 1: implementing a general class public class Class2: IMyClass3 <String> {public void SayHello (string msg) {Console. writeLine (msg);} pub Lic string Sayhi () {throw new NotImplementedException () ;}}// 2: generic classes implement generic interfaces // here, the U of IMyClass3 <U> is determined by the U in the class interface. Public class Class3 <U>: IMyClass3 <U> {public void SayHello (U msg) {Console. writeLine (msg);} public U Sayhi () {throw new NotImplementedException ();}}

2. Create an index

Public class MyClass {private string [] _ data = new string [5]; /// <summary> /// define an index /// </summary> public string this [int index] {get {return _ data [index];} set {_ data [index] = value ;}}}
Create a generic index
Public class MyClass <T> {private T [] _ data = new T [5]; /// <summary> /// define an index /// </summary> // public T this [int index] {get {return _ data [index];} set {_ data [index] = value ;}}}
 

Iii. Generic Constraints

Add where T: struct/class to the back of the generic. It indicates that T will be replaced in the defined constraint in the future.

Var p = new Person (); var etor = p. getEnumerator (); while (etor. moveNext () {Console. writeLine (etor. current. toString ();} Console. writeLine ("OK"); Console. readKey ();

Implementation of specific classes

Public class Person: IEnumerable {private string [] friends = new string [] {"11", "22", "33"}; public string Name {get; set ;} public int Age {get; set;} public IEnumerator GetEnumerator () {return new PersonEnumerator (this. friends); // The returned Object type} public class PersonEnumerator: IEnumerator {private string [] _ friends; public PersonEnumerator (string [] fs) {_ friends = fs ;} private int index =- 1; // subscript refers to the first digit of 0 // obtain the data public object Current {get {if (index> = 0 & index <_ friends. length) {return _ friends [index]; // return values by subscript.} Else {throw new Exception () ;}}// move the subscript public bool MoveNext () {if (index + 1 <_ friends. length) {index ++; return true;} return false;} // restore the subscript and initialize public void Reset () {index =-1 ;}}
V. yield Method

The yield keyword instructs the compiler that its method is an iterator block. The compiler generates a class to implement the behavior represented in the iterator block. In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerated object. This is a return value, for example, the value returned in each loop of the foreach statement. The yield keyword can also be used with break to indicate the end of iteration.

Vi. File Operations

String path = @ "F: \ VS2008 \ Projects \ ShiPinJiChu _ HeiMa \ file operation \ bin \ Debug \ file operation .exe. config "; // obtain the file name Console. writeLine (Path. getFileName (path); // obtain the file suffix Console. writeLine (Path. getExtension (path); // obtain the file name Console without a suffix. writeLine (Path. getFileNameWithoutExtension (path); // obtain the Console of the Directory section of the path. writeLine (Path. getDirectoryName (path); // modify the file suffix Console. writeLine (Path. changeExtension (path, "dll"); // merge two paths str Ing path1 = @ "F: \ VS2008 \ Projects \"; string path2 = "xiaohui.exe"; Console. writeLine (Path. combine (path1 + path2); // return the path of the temporary folder of the current user. Console. WriteLine (Path. GetTempPath (); // create a temporary file named zero byte on the disk and return the complete Path of the file. Console. WriteLine (Path. GetTempFileName (); Console. ReadKey ();

* Basic Directory Operations <Directory>

// Create a Directory for (int I = 0; I <10; I ++) {Directory. createDirectory (@ "C: \" + I);} Console. writeLine ("OK"); Console. readKey (); // Delete the Directory for (int I = 0; I <10; I ++) {// Directory. delete (@ "C: \" + I); // only the empty Directory can be deleted. delete (@ "C: \" + I, true);} Console. writeLine ("OK"); Console. readKey (); // cut Directory. move (@ "C: \ 11", @ "C: \ 222 \ 11"); // rename <using cut to implement> Directory. move (@ "C: \ 222", @ "C: \ 333"); Console. writeLine ("OK"); Console. readKey (); // obtain all subdirectories under the file string path = @ "C: \ 333 \ 11"; var file = Directory. getFiles (path); foreach (var item in file) {Console. writeLine (item);} // Delete Directory. delete (@ "C: \ 333", true); Console. writeLine ("OK"); Console. readKey ();

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.