In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Most people do not understand the knowledge points of this article "how to declare and use the delegation in C#", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article, let's take a look at this "how to declare and use the commission in C#" article.
If you want to pass a method parameter to a method, you can use a delegate. To pass a method, the details of the method must be encapsulated in a new type of object, the delegate. A delegate is a special type of object, which is special in that all objects we have previously defined contain data, while a delegate contains only the address of one or more methods.
In the .NET version, the delegate points to the address of the method. In C++, a function pointer is a pointer to a memory location, but it is not type safe. Developers cannot tell what the pointer actually points to, let alone items such as parameters and return values.
.net delegates are type-safe classes that define the types that return types and parameters. A delegate class contains not only references to methods, but also references to multiple methods.
1. Declaration delegation
Using delegates, like using classes, requires two steps: definition and instantiation. You must first define the delegate to use, and for a delegate, defining it is a method that tells the compiler which type of delegate represents. You must then create one or more instances of the delegate to use. The compiler creates a class that represents the delegate in the background.
Define the syntax of the delegate:
Delegate void IntMethod (int x); / / defines a delegate IntMethod, specifying that each instance of the delegate can contain a reference to one or more methods, the referenced method must take an int parameter and return void.
Because defining a delegate is basically defining a new class, you can define a delegate anywhere you define the class. You can also use modifiers such as public,private,protected on the definition of a delegate.
The delegate is derived from the base class System.MulticastDelegate,MulticastDelegate and from the base class System.Delegate.
There are two different terms for a class: "class" for a broad definition, "object" for an instance of a class. But there is only one term for delegation. When you create an instance of a delegate, the instance you create is still called a delegate. The specific meaning of the delegate must be determined from the context.
two。 Use delegation
Once the delegate is defined, you can create an instance of it and use it to store the details of a particular method.
Delegate void IntMethod (int x); static void Fun (int x) {Console.WriteLine (x);} static void Main () {int x = 40; IntMethod intMethod = new IntMethod (Fun); intMethod (x); Console.ReadKey ();}
A delegate always syntactically accepts the constructor of a parameter, which is the method referenced by the delegate. This method must match the signature when the delegate was originally defined.
Use the name of the delegate instance, followed by parentheses, and if you need parameters, you must add parameters in parentheses.
Providing parentheses to the delegate instance is exactly the same as the Invoke () method that calls the delegate class:
IntMethod (x); intMethod.Invoke (x)
To reduce input, you only need to pass the name of the method address to the delegate instance, which is called delegate inference.
IntMethod intMethod = new IntMethod (Fun); IntMethod intMethod = Fun
Delegate inference can be used anywhere you need a delegate instance. Delegate inference can also be used for events because events are based on delegates. (there is an introduction in the following article)
Note that you can use a delegate to call a method of any type of object, whether static or instance.
3. Define two methods in a class using the delegate array / / first: class MathOperations {public static double MultiplyByTwo (double value) {return value * 2;} public static double Square (double value) {return value * value }} / / define a delegate delegate double DoubleOp (double x) that returns a double type with a double type parameter Class Program {static void Main () {/ / instantiate the delegate array, just like the array of the instantiated class DoubleOp [] operations = {MathOperations.MultiplyByTwo, MathOperations.Square} / / iterate through the array, using each delegate instance in the array for (int I = 0; I < operations.Length; iTunes +) {Console.WriteLine ("Using operations [{0}]:", I) / / pass the delegate instance as a parameter to the ProcessAndDisplayNumber method ProcessAndDisplayNumber (operations [I], 2.0); ProcessAndDisplayNumber (operations [I], 7.94); ProcessAndDisplayNumber (operations [I], 1.414); Console.WriteLine () }} static void ProcessAndDisplayNumber (DoubleOp action, double value) {/ / invoke the delegate in ProcessAndDisplayNumber to execute the method referenced by the delegate instance double result = action (value); Console.WriteLine ("Value is {0}, result of operation is {1}", value, result) }} 4.Action and Func delegation
In addition to defining a delegate type for each parameter and return type, you can also use Action and Func delegates.
A generic Action delegate represents a method that references a void return type. There are different variants of this delegate class and can pass up to 16 different parameter types. The Action class without generic parameters invokes methods without parameters. Action calls the method with one parameter, Action calls the method with two parameters, and so on.
The Func delegate allows methods with return types to be called. Like Action, Func has different variants that can pass up to 16 different parameter types and one return type. Func delegate types can call methods that have no parameters and have a return type.
The following uses Func delegates to implement a function that is difficult to write without a delegate: sort an array of objects, it is easy to sort objects of value types such as int or string, and you need to write a lot of code if you want to sort objects of many custom types. Using delegates reduces the amount of code.
Define the class that contains the comparison method:
The BubbleSorter class implements a generic method Sort, with the first parameter being the array of objects to be sorted, and the second a delegate passing the method to compare the two objects. This allows you to pass custom comparison methods to the Sort method.
Class BubbleSorter {static public void Sort (IList sortArray, Func comparison) {bool swapped = true; do {swapped = false; for (int I = 0; I < sortArray.Count-1) Compare two objects if (comparison (sortArray [I + 1], sortArray [I]) {T temp = sortArray [I]; sortArray [I] = sortArray [I + 1] SortArray [I + 1] = temp; swapped = true;} while (swapped);}}
Define a custom class
Class Employee {public Employee (string name, decimal salary) {this.Name = name; this.Salary = salary;} public string Name {get; private set;} public decimal Salary {get; private set } public override string ToString () {return string.Format ("{0}, {1Name C}", Name, Salary);} public static bool CompareSalary (Employee e1, Employee e2) {return e1.Salary < e2.Salary;}}
Client code:
Employee [] employees = {new Employee ("Bugs Bunny", 20000), new Employee ("Elmer Fudd", 10000), new Employee ("Daffy Duck", 25000), new Employee ("Wile Coyote", 1000000.38m), new Employee ("Foghorn Leghorn", 23000), new Employee ("RoadRunner", 50000)} / / Sort executes custom Employee.CompareSalary methods BubbleSorter.Sort (employees, Employee.CompareSalary); foreach (var employee in employees) {Console.WriteLine (employee);} 5. Multicast delegation
Each delegate described earlier contains only one method call, and the delegate can also contain multiple methods. This kind of delegate is called multicast delegate.
If you call a multicast delegate, you can call multiple methods sequentially, but if the delegate's signature does not return void, you can only get the result of the last method called by the delegate.
Use + = add method,-= delete method.
Static void Main () {Action operations = MathOperations.MultiplyByTwo; operations + = MathOperations.Square; ProcessAndDisplayNumber (operations, 2.0); ProcessAndDisplayNumber (operations, 7.0); Console.WriteLine ();} static void ProcessAndDisplayNumber (Action action, double value) {Console.WriteLine (); Console.WriteLine ("ProcessAndDisplayNumber called with value = {0}", value) Action (value);} class MathOperations {public static void MultiplyByTwo (double value) {double result = value * 2; Console.WriteLine ("Multiplying by 2: {0} gives {1}", value, result) } public static void Square (double value) {double result = value * value; Console.WriteLine ("Squaring: {0} gives {1}", value, result);}}
Each time the ProcessAndDisplayNumber method is called, two methods in the action delegate instance are called sequentially.
Output:
ProcessAndDisplayNumber called with value = 2 Multiplying by 2: 2 gives 4 Squaring: 2 gives 4 ProcessAndDisplayNumber called with value = 7 Multiplying by 2: 7 gives 14 Squaring: 7 gives 49
Delegates can also use the +,-operator:
Action operations1 = MathOperations.MultiplyByTwo; Action operations2 = MathOperations.Square; Action operations = operations1 + operations2; operations = operations-operations2
A multicast delegate contains a collection of delegates that are called one by one. If one of the methods throws an exception, the entire iteration stops.
Static void One () {Console.WriteLine ("One"); throw new Exception ("Error in one");} static void Two () {Console.WriteLine ("Two");} static void Main () {Action D1 = One; D1 + = Two; try {D1 () } catch (Exception) {Console.WriteLine ("Exception caught");}}
The delegate only calls the first method. Because the first method throws an exception, the iteration of the delegate stops and the Two () method is no longer called.
To avoid this problem, use the GetInvocationList () method defined by the Delegate class, which returns an array of Delegate objects:
Action D1 = One; D1 + = Two; Delegate [] delegates = d1.GetInvocationList (); foreach (Action d in delegates) {try {d ();} catch (Exception) {Console.WriteLine ("Exception caught");}}
Output:
One Exception caught Two
Using the GetInvocationList () method, you can pass different parameters for each method of the delegate, and get the return value of each method.
Static int One (int x) {return x;} static int Two (int x) {return x;} static void Main () {Func D1 = One; D1 + = Two; Delegate [] delegates = d1.GetInvocationList (); Func D2 = (Func) delegates [0]; Console.WriteLine (D2 (1)); Func D3 = (Func) delegates [1] Console.WriteLine (d3 (2)); Console.ReadKey ();}
Output:
1 26. Anonymous method
Using anonymous methods, you can assign the method body directly to the delegate instance without defining a method.
Static void Main () {string mid = ", middle part,"; Func anonDel = delegate (string param) {param + = mid; param + = "and this was added to the string."; return param;}; Console.WriteLine (anonDel ("Start of string"));}
Instead of assigning the method name to the delegate variable anonDel, the above code is preceded by the keyword delegate and the argument list. When using anonymous methods, you can use external variables.
The advantage of anonymous methods is that they reduce the amount of code. Using anonymous methods, the code execution is not accelerated. The compiler still defines a method that has only one name that is automatically specified.
To use anonymous methods, you must follow two rules:
(1)。 Jump statements (break,goto,continue) cannot be used in anonymous methods to call outside the anonymous method, nor can external code be called inside the anonymous method.
(2)。 Insecure code cannot be accessed internally by anonymous methods. Nor can you use ref and out in anonymous methods
If you need anonymous methods to write the same function multiple times, don't use anonymous methods.
The above is about the content of this article on "how to declare and use the delegation in C#". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.