简体   繁体   English

使用Func在函数中实现泛型

[英]Implementing generics in a function using Func

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. 其中MyClass.code是获取MyClass并返回字符串的静态函数(在MyClass中定义)。

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(); 问题是当我尝试将这个函数与List<int>List<double> ,我现在正在预定义像Func<int,string> intCoder = (x) => x.ToString(); and Func<double,string> (x) => x.ToString(); 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);

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. 碰巧的是, Convert.ToString具有适当的签名的重载

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). int.ToString的问题在于,它的重载都没有适当的签名(它们没有采用int参数,因为它暗含了)。 In that case there would be nothing you could do apart from defining an adapter function. 在这种情况下,除了定义适配器功能之外,您将无能为力。

You don't have to declare a variable for the func. 您不必为func声明变量。 You can just put the lambda expression as the parameter value 您可以将lambda表达式作为参数值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM