Implementing generics in a function using Func

时间秒杀一切 提交于 2019-12-14 04:07:37

问题


I have a follow static function:

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

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

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

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

The problem is when I try to use this function with List<int> or List<double> what I do now is predefining statics like Func<int,string> intCoder = (x) => x.ToString(); and Func<double,string> (x) => x.ToString(); and use them. Is there another way of doing that? something like:

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

回答1:


You can do this with

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

It just so happens that Convert.ToString has an overload with the appropriate signature.

The problem with int.ToString is that none of its overloads have the appropriate signature (they don't take an int parameter as it is implied). In that case there would be nothing you could do apart from defining an adapter function.




回答2:


You don't have to declare a variable for the func. You can just put the lambda expression as the parameter value

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


来源:https://stackoverflow.com/questions/13026128/implementing-generics-in-a-function-using-func

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!