When processing multiple methods with similar parameters and returning types, but implementing different methods, you need to dynamically call these methods according to the method name. In C#, the use of commission is an effective solution.
In the example provided, the goal is to create a method, which uses the name of another method as a parameter and calls the method. Because the parameters of require a specific method signature, complexity will occur.
.NET Framework provided a commission called RunTheMethod
, allowing us to specify a type of security method signature. By using , we can define the RunTheMethod
parameters as a method that accepts a string parameter and return an integer.
The following is the implementation after modification: Func
Func
RunTheMethod
Through this modification, we can now pass different methods as parameters to
public bool RunTheMethod(Func<string, int> myMethodName) { int i = myMethodName("My String"); return true; }
The above is the detailed content of How Can I Pass Methods as Parameters in C# Using Delegates?. For more information, please follow other related articles on the PHP Chinese website!