30 Days C # Foundation Consolidation------Understanding delegates, string exercises

Source: Internet
Author: User

----> Understand delegates.

Examples of life: I want a lawsuit, I need to find a lawyer, the court above the lawyer to defend the client, it really executes is the client's statement, then the lawyer is tantamount to a Commission object. The parties entrust a lawyer to justify themselves.

A delegate in C # is a class, (class type), because only the class has the concept of an object. A delegate in C # can be understood as a wrapper for a function that allows a function in C # to be passed as a parameter.

Definition of a delegate:

        Define delegate public        delegate void mydelegate (int para1,string para2);

Some of the commissioned steps:

1: Define the delegate type (method is similar to the declaration of the method)

        public delegate void MyDelegate (int para1,int para2);

2: Declaration delegate, since the delegate is a type, you can declare a delegate variable by using a delegate.

        MyDelegate D;

3: Instantiate the delegate, and pass the parameter (method) in.

        D=new MyDelegate (new program (). ADD);

4: The delegate type is passed as a parameter to another method.

        MyMethod (d);     

5: The delegate is invoked in the method.

        private static void MyMethod (MyDelegate mydelegate)        {            ///5: Delegate MyDelegate is called in the method            ;        }

Considerations for Delegation:

1: The definition delegate can only use the delegate keyword, the instantiation of the delegate is a method name (without parentheses) as a parameter, and the definition of the method conforms to the definition of the delegate, that is, the method's return value type, the number of arguments, the type must be the same as in the delegate definition.

2: A delegate can take a method as an argument to another method, which can be thought of as an object of a wrapper method. Its invocation, like the invocation of a method, must be of the same type and number of arguments as the delegate definition.

The delegation I now understand is to pass the method as a parameter. The sum of the last method in the following image is called the previous add () method.

<summary>///Commissioned study///</summary> class Program {//1: Use delegate to define delegate public de        legate void mydelegate (int para1,int para2);            static void Main (string[] args) {//2: Declaration of entrustment MyDelegate D; 3: Instantiate the delegate, pass a method (the method after instantiation), D=new mydelegate (new program ().            ADD);            4: The delegate type is passed as a parameter to another method.           MyMethod (d);        D here is equivalent to the method add, which we passed into the MyMethod () method.        }//This method definition must be the same as the delegate definition, that is, the return type is void and two arguments are int.            private void Add (int para1,int para2) {int sum = para1 + para2;            Console.WriteLine ("Two number of the and for:" +sum);        Console.readkey ();        The argument to the}//method is the delegate type.        private static void MyMethod (MyDelegate mydelegate) {///5: Delegate mydelegate is invoked in the method; }    }

Exercises for delegates:

Implement a greeting method, but each country is not the same, we need to use the delegate to achieve.

    <summary>///delegate instance///</summary> class Program {public delegate void Greetingdele        Gate (string name);        Defines a delegate, a parameter. static void Main (string[] args) {//Introduce a delegate//the general feeling here is not to declare an instantiation of a delegate, just like to instantiate a program, and note that while the program is instantiated here,            In fact, it is the instantiation of the greetingdelegate.                                         Program P=new program ();               P.greeting ("Fai", p.chinesegreeting);            The method of the delegate, where the arguments are the methods of each of our countries.            P.greeting ("Zhang Hui", p.englishgreeting);        Console.readkey ();        }///<summary>///delegate as a parameter, in the method to invoke the method of passing. </summary>//<param name= "name" ></param>//<param name= "callback" ></param > public void Greeting (String name,greetingdelegate callback) {//Call Delegate callback (NAM        e);      }//English public void englishgreeting (string name) {Console.WriteLine ("Hello," +name);  }//Chinese public void chinesegreeting (string name) {Console.WriteLine ("Hello," +name); }    }

Note that our practice and the above differences, we are directly follow the steps above, each step is not omitted, here we just instantiate the program, our above example can be abbreviated to this.

        static void Main (string[] args)        {            ////2: declaration of entrustment            //mydelegate D            ; 3: Instantiate the delegate, pass a method (the method after instantiation),            //d=new mydelegate (new program (). ADD);            4: The delegate type is passed as a parameter to another method.            //mymethod (d);           D here is equivalent to the method add, which we passed into the MyMethod () method. Program            d=new Program ();            MyMethod (D.add);        }

Exercises about strings and so on.

EG--01:123-456--7--89-----123-----2, remove the repeating symbol in a similar string. Returns the form of 123-456-7-89-123-2.

            String str = "123-456--7--89-----123-----2";            string[] STSR = str. Split ("-". ToCharArray (), stringsplitoptions.removeemptyentries); First, divide the string into a character array, and remove the "-"              str=string. Join ("-", STSR);                     Use join to concatenate each item in a character array through "-".             Console.WriteLine (str);            Console.readkey ();

EG-02: Extracts the file name from the file path (including the suffix), such as: C:/a/b.txt extracts the name of B.txt.

            String str = "C:/a/b.txt";       The paths we get through file are all strings.              string path = Path.getfilename (str);            Console.WriteLine (path);            Console.readkey ();

EG-03: "192.168.10.5[port=21,type=ftp]", please use the program to resolve this string, print "IP address for,,, Port is,,, provide service ..." "

Method 1:

            String str = "192.168.10.5[port=21,type=ftp]";            int a = str. IndexOf (' = ');      Gets the address of the byte ' = ' to            string port = str. Substring (++a, 2);//intercept the data behind            int b = str. IndexOf (' [');            string ip = str. Substring (0, b);            int c = str. IndexOf (' e ');                String type = str. Substring (c + 2, 3);            Console.WriteLine (IP);                        Console.WriteLine (port);            Console.WriteLine (type);            Console.WriteLine ("IP address is {0}, port number is {1}, service provided is {2}", Ip,port,type);            Console.readkey ();

Method 2:

            string S1 = "192.168.1.5[port=21,type=ftp]";            String s2 = "192.168.10.5[port=21]"; The first is IP string[] temps = S1. Split ("[]".            ToCharArray (), stringsplitoptions.removeemptyentries);            string ip = temps[0];            The following is a key-value pair. string[] Subtemps = temps[1].            Split (', ');            Dictionary<string,string> dic=new dictionary<string, string> (); for (int i = 0; I <subTemps.Length; i++) {string[] ss = Subtemps[i].                Split (' = '); Dic.                 ADD (Ss[0],ss[1]);            The keys and values are placed in the collection. } dic.            ADD ("IP", Temps[0]); if (!dic. ContainsKey ("Type")) {dic.            ADD ("Type", "fttp");                }//Loop output in the collection of keys and values foreach (Keyvaluepair<string, string> item in DIC) { Console.WriteLine (item. key+ ":" +item.            Value); } console.readkey ();

30 days C # Foundation Consolidation------Understanding delegates, string exercises

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.