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 to learn the C language pointer, it is a very tangled feeling, always feel to call a method directly call 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")] public delegate void 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 void Test5 (int a, int b, int c) { //... } No parameter no return value private static void Test1 () { Console.WriteLine ("Func Test1, no Parameter"); } There is no return value for parameter private static void Test2 (String str) { Console.WriteLine ("Func Test2, Parameter is" + str); c13/>} //No parameter has return value private static Object Test3 () { Console.WriteLine ("Func Test3, Parameter"); Return Guid.NewGuid (). ToString (); } The parameter has a return value of private static object Test4 (String strres) { Console.WriteLine ("Func Test4, Parameter and Return Value "); return strres; }
Call:
static void Main (string[] args) { //1. No parameter no return value method var oAction1 = new Action (Test1); Oaction1.invoke ();//Call Mode one oAction1 ();//Call Mode two //2. Parameter no return value var oAction2 = new Action<int, int, int> ( TEST5); Oaction2.invoke (1, 2, 3); OAction2 (1, 2, 3); anonymous method calls var OAction3 = new Action<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 oFunc1 = new func<object> (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 lsttest = 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 ofunc = new func<string, bool> (testwhere); lstres = Lsttest.where (Ofunc);
is not the same as the ~ ~
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> ();p ublic delegate TResult Myfunc<in T, 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:
Class Program {static void Main (string[] args) {person strhelper = new person (); string r1 = Strhelper.processfunc ("Chinese", "Hello", New MyDelegate (Strhelper.chinesesayhello)); string r2 = Strhelper.processfunc ("中文版", "Hello", New MyDelegate (Strhelper.englishsayhello)); String r3 = Strhelper.processfunc ("Japanese", "こんにちは", New MyDelegate (Strhelper.japanesesayhello)); Console.WriteLine (R1); Console.WriteLine (R2); Console.WriteLine (R3); Console.readkey (); }} public delegate string MyDelegate (string s1, string s2); public class Person {public string Processfunc (string s1, string s2, mydelegate process) {RE Turn process (s1, S2); public string Chinesesayhello (string s1, string s2) {return S1 + "," + S2; } public string Englishsayhello (string s1, string s2) {RETUrn S1 + "," + S2; public string Japanesesayhello (string s1, string s2) {return S1 + "," + 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 class Person {public virtual string SayHello (String s2) {return s2; }}public class Chinese:person {public override string SayHello (String s2) {return ' Chinese , "+ s2; }} public class English:person {public override string SayHello (String s2) {return "中文版," + S2; }} public class Japanese:person {public override string SayHello (String s2) {return "Japanese," + S2; The}//main function calls class program {static void Main (string[] args) {var r1 = Getperson ("Hello"). S Ayhello ("Hello"); var r2 = Getperson ("Hello"). SayHello ("Hello"); var r3 = Getperson ("こんにちは"). SayHello ("こんにちは"); Console.WriteLine (R1); Console.WriteLine (R2); Console.WriteLine (R3); Console.readkey (); } public static Person Getperson (string strtype) { if (strtype = = "Hello") return new Chinese (); else if (strtype = = "Hello") return new 中文版 (); else return new Japanese (); } }
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