Implementing generics in functions using Func

I have the following static function:

public static string codeList<T>(List<T> thelist, Func<T, string> coder); 

using this function with my own objects is not a problem, for example:

 string code = codeList<MyClass>(myclassList, MyClass.code); 

Where MyClass.code is a static function (defined in MyClass) that receives MyClass and returns a string.

The problem is that when I try to use this function using List<int> or List<double> , what I am doing now predetermines statics like Func<int,string> intCoder = (x) => x.ToString(); and Func<double,string> (x) => x.ToString(); and uses them. Is there any other way to do this? sort of:

 string code = codeList<int>(intList, Int32.ToString); 
0
source share
2 answers

You can do it with

 string code = codeList<int>(intList, Convert.ToString); 

It so happened that Convert.ToString has an overload with the corresponding signature.

The problem with int.ToString is that none of its overloads has a corresponding signature (they do not accept the int parameter as implied). In this case, you cannot do anything other than determine the function of the adapter.

+2
source

You do not need to declare a variable for func. You can simply put the lambda expression in the parameter value

 string code = codeList(intList, i => i.ToString()); 
+1
source

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


All Articles