How to write a method with delegation option in C # /. NET 4.0?

I use the method of declaring a delegate at the class level:

protected delegate void FieldsDelegate(); //and then write a method eg protected int CreateComponent(DbConnection cnctn, string tableName, Dictionary<string, object> changedFieldValues, FieldsDelegate fieldsDelegate) 

However, this is really cumbersome, and I cannot immediately see what a delegate is. Therefore, I would like to do it as follows:

 protected int CreateComponent(DbConnection cnctn, string tableName, Dictionary<string, object> changedFieldValues, delegate void fieldsDelegate()) 

so that I don’t have a separate definition.

The above is not allowed for any reason. So how can I do this?

+6
source share
2 answers

.NET now provides Action and Func generics for this purpose.

In your case, this delegate does not accept any parameters and returns nothing.

 // protected delegate void FieldsDelegate(); // Don't need this anymore protected int CreateComponent( DbConnection cnctn, string tableName, Dictionary<string, object> changedFieldValues, Action fieldsDelegate ) 

If a string was required as a parameter:

 // protected delegate void FieldsDelegate(string s); protected int CreateComponent( DbConnection cnctn, string tableName, Dictionary<string, object> changedFieldValues, Action<string> fieldsDelegate ) 

If he took the string as a parameter and returned bool:

 // protected delegate bool FieldsDelegate(string s); protected int CreateComponent( DbConnection cnctn, string tableName, Dictionary<string, object> changedFieldValues, Func<string, bool> fieldsDelegate ) 
+12
source

You can use the common Action<T> and Func<T> and their variants as delegates, and the bonus is that you don’t need to define a separate delegate at all.

Action<T> accepts up to 16 different type parameters, therefore: Action<T1, T2> and up; Each type parameter is a type parameter for a method in the same position. So Action<int, string> will work for this method:

 public void MyMethod(int number, string info) 

Func<T> is the same, except for those that return a value. The argument of the last type is the return type. Func<T> not what you would use in your case here.

Example: Func<string, int, object> will be for a method such as:

 public object MyOtherMethod(string message, int number) 

Using these common delegates makes it clear what arguments for this delegate argument will be, which seems to be your intention.

 public void MyMethod(Action<string, MyClass>, string message) 

By calling this method, you know that you need to pass a method that uses string and MyClass .

 public void MeOtherMethod(Func<int, MyOtherClass>, int iterations) 

Here you know that you need to pass a method that takes an int parameter and returns MyOtherClass

+5
source

Source: https://habr.com/ru/post/886780/


All Articles