问题
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