C # Basic Series--delegate implementation of simple design patterns

Source: Internet
Author: User

Preface: The previous article introduced the next multi-threaded knowledge: C # Basic series-Multi-threading common use of the details, which refers to the delegate variable. This article briefly describes the use of the delegate. Of course, many of the articles commissioned in the garden will say: The concept of the Commission and the event is like a barrier, the person who passed the threshold, it is really easy, and no past people every time to see the Commission and events feel nervous. Indeed, this thing is like the first time to learn the C # language pointer, there is a very tangled feeling, always feel to call a method call directly on the line, why do you want to define a delegate when the method is executed. In fact, in C # Many of the technology is to reuse and simplify the code, the trust is no exception, many use C # polymorphic to implement the design pattern can be used to rewrite the way, can be understood as a lightweight design pattern bar. Bo Master intends to draw a special share under the polymorphism and commissioned to achieve the similarities and differences of design patterns. This article first introduces the use of simple delegates.

What is a delegate: a Delegate in C # (Delegate) is similar to a pointer to a function in C or C + +. In the blogger's words, a delegate is a reference type that allows a method name to be passed as a parameter. It defines the type of method, which can be said to be the abstraction of a method, then conversely, the method can be understood as an instance of a delegate, such as public delegate void Testdelegate (String str); This delegate defines an abstraction for all methods that have a parameter type of string and no return value.

Second, why to use the Commission: Remember Bo Master just started to do the project when see the delegation of the head big, always feel it is nothing, the only advantage seems to be the code looks cool ~ ~ With the accumulation of work, found that some small requirements of the project using this lightweight delegate to achieve the time can really reduce the amount of code.

Third, the use of the Commission:

1. Delegate types inside the. Net Framework: Friends who have used a delegate may notice that there are two types of delegate variables defined in C # that basically meet our general needs.

(1)Delegate of action type: C # defines the action delegate used to abstract a method that has no return value . To go to the definition of the action variable is the simplest form:

    // Summary:      //      encapsulates a method that does not have parameters and does not return a value.     [Typeforwardedfrom ("system.core, version=3.5.0.0, Culture=neutral, publickeytoken= b77a5c561934e089")]    publicdelegatevoid Action ();

It is defined as a delegate that has no parameters without a return value. The action also provides a delegate of 16 generics that defines the passed-in parameters of the method:

Let's see how they're used, and we'll start by defining the method of testing:

        Private Static voidTEST5 (intAintBintc) {//......        }        //No parameter no return value        Private Static voidTest1 () {Console.WriteLine ("Func Test1, No Parameter"); }        //There are no return values for parameters        Private Static voidTest2 (stringstr) {Console.WriteLine ("Func Test2, Parameter is"+str); }        //no parameter has return value        Private Static ObjectTest3 () {Console.WriteLine ("Func Test3, Parameter"); returnGuid.NewGuid ().        ToString (); }        //There are parameters with return values        Private Static ObjectTest4 (stringstrres) {Console.WriteLine ("Func Test4, Parameter and Return Value"); returnStrres; }

Call:

        Static voidMain (string[] args) {            //1. No parameter no return value method            varOAction1 =NewAction (TEST1); Oaction1.invoke ();//Call mode oneOAction1 ();//Call mode two//2. No return value for a parameter            varOAction2 =Newaction<int,int,int>(TEST5); Oaction2.invoke (1,2,3); OAction2 (1,2,3); //invocation of anonymous methods            varOAction3 =Newaction<int,int,int> ((a,b,c) = {                 //......            }); Oaction3.invoke (1,2,3); }

(2) Func type delegate: Remember the parameters of the extension method where (), Select (), and so on in LINQ. public static ienumerable<tsource> where<tsource> (this ienumerable<tsource> source, func< TSource, bool> predicate). The parameter here is a delegate of type Func. A delegate of type Func in C # is used to handle methods that have parameters with return values. not much to say, on the code:

 static  void  Main (string  [] args) { var  Ofun C1 = new  func< (TEST3);             var  ofuncRes1 = Ofunc1.invoke ();  var  oFunc2 = new  Func<string , object  > (TEST4); OFUNC2 (  a   "         ); }

Knowing the method of Func can be used to think of our magical lamada expression, in fact Lamada expression is an anonymous delegate.

var New list<string>(); var lstres = lsttest.where (x = X.contains ("_"));

The Lamada expression in this where we take him apart:

Private Static BOOL Testwhere (string  x) {     return x.contains ("_" );}
var New func<stringbool>= lsttest.where (Ofunc);

2. Custom delegate:

 Public Delegate void Testdelegate (string str);

In fact, many people should have written their own action, Func type of delegate. In fact, it is simple to define a generic delegate yourself:

 Public Delegate void myaction< in t>();  Public Delegate TResult myfunc< in Out tresult> (T Arg);

In fact, there is basically no difference between the action and the Func used by the system.

3, the merger and disassembly of the delegate is placed in the event to share. This article and the ...

4, if according to the above method to use the delegate, it is really awkward dead, because the call method is called directly with the method name is good, why also define a delegate variable to call, this is not to complicate the simple problem. Indeed, the above is just the code written to introduce the delegate, which is certainly not used in the actual project. In fact, a delegate is generally used in a project to pass a delegate variable as a parameter or function callback. Look at the following code:

classProgram {Static voidMain (string[] args) {Person Strhelper=NewPerson (); stringR1 = Strhelper.processfunc ("Chinese","Hello",Newmydelegate (Strhelper.chinesesayhello)); stringr2 = Strhelper.processfunc ("中文版","Hello",Newmydelegate (Strhelper.englishsayhello)); stringR3 = Strhelper.processfunc ("Japanese","こんにちは",Newmydelegate (Strhelper.japanesesayhello));            Console.WriteLine (R1);            Console.WriteLine (R2);            Console.WriteLine (R3);        Console.readkey (); }    }     Public Delegate stringMyDelegate (stringS1,stringS2);  Public classPerson { Public stringProcessfunc (stringS1,stringS2, mydelegate process) {            returnprocess (S1, S2); }         Public stringChinesesayhello (stringS1,stringS2) {            returnS1 +","+S2; }         Public stringEnglishsayhello (stringS1,stringS2) {            returnS1 +","+S2; }         Public stringJapanesesayhello (stringS1,stringS2) {            returnS1 +","+S2; }    }

Get results:

The public string Processfunc (string s1, string s2, mydelegate process) defines a callback function that can be passed to any method that conforms to the delegate to obtain the desired result. To look closely at this design is very similar to the factory design pattern, I have simply constructed a factory:

 Public classPerson { Public Virtual stringSayHello (stringS2) {            returnS2; }    } Public classChinese:person { Public Override stringSayHello (stringS2) {            return "Chinese,"+S2; }    }     Public classEnglish:person { Public Override stringSayHello (stringS2) {            return "中文版,"+S2; }    }     Public classJapanese:person { Public Override stringSayHello (stringS2) {            return "Japanese,"+S2; }    }//called inside the main functionclassProgram {Static voidMain (string[] args) {            varR1 = Getperson ("Hello"). SayHello ("Hello"); varr2 = Getperson ("Hello"). SayHello ("Hello"); varR3 = Getperson ("こんにちは"). SayHello ("こんにちは");            Console.WriteLine (R1);            Console.WriteLine (R2);            Console.WriteLine (R3);        Console.readkey (); }         Public StaticPerson Getperson (stringstrtype) {            if(Strtype = ="Hello")                return NewChinese (); Else if(Strtype = ="Hello")                return New中文版 (); Else                return NewJapanese (); }            }

The results are the same as above:

Such a comparison is not the use of the delegate a little feel it ~ ~ If you are not afraid of trouble, you can use it in the project to try, I believe you will have a harvest ~ ~

C # Basic Series--delegate implementation of simple design patterns

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.