How to use a C # delegate to call different methods, each of which has a different parameter?

The following question and answer discusses the use of the out parameter in a delegate:

Func <T> with out parameter

I need to take one more step. I have several conversion methods (functions) where I would like to use a delegate. For example, let's start with the methods below:

private bool ConvertToInt(string s, out int value) { try { value = Int32.Parse(s); return true; } catch (Exception ex) { // log error value = 0; } return false; } private bool ConvertToBool(string s, out bool value) { try { value = Convert.ToBoolean(s); return true; } catch (Exception ex) { // log error value = false; } return false; } 

Then I declared the following delegate:

 delegate V ConvertFunc<T, U, V>(T input, out U output); 

What I would like to do is something like this (pseudocode):

 if (do int conversion) func = ConvertToInt; else if (do boolean conversion) func = ConvertToBool; else ... 

Only the compiler allows you to explicitly declare delegate identifiers as follows:

 ConvertFunc<string, int, bool> func1 = ConvertToInt; ConvertFunc<string, bool, bool> func2 = ConvertToBool; 

How can I declare a single identifier to which I can assign one of several methods that follow the above pattern (depending on the type of conversion I want to perform)?

Update:

Assuming a dictionary containing value / object pairs:

 private Dictionary<string, object> dict = new Dictionary<string, object>(); 

With values ​​such as:

 this.dict.Add("num", 1); this.dict.Add("bool", true); 

Based on the answer, I was able to implement my delegate as follows:

 public T GetProperty<T>(string key) { ConvertFunc<string, T, bool> func = ConvertToT<T>; object val = this.dict[key]; T result; if (func(key, out result)) return result; else return default(T); } 
+4
source share
1 answer

I think you are looking for something like

 private bool ConvertToT<T>(string s, out T value) { try { value = (T)Convert.ChangeType(s, typeof(T)); return true; } catch (Exception ex) { // log error // not sure what you're trying here? value = default(T); } return false; } 
+6
source

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


All Articles