使用Func在函数中实现泛型 [英] Implementing generics in a function using Func

查看:169
本文介绍了使用Func在函数中实现泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关注静态函数:

  public static string codeList< T>(List< T> thelist,Func< T,string>编码器); 

使用这个函数与我自己的对象不是问题,例如:

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

其中MyClass.code是一个静态函数(在MyClass中定义),它获取MyClass并返回字符串。 / p>

问题是当我尝试使用 List< int> List< ; double> 我现在所做的是预定义静态,如 Func< int,string> intCoder =(x)=> x.ToString(); Func< double,string> (x)=> x.ToString(); 并使用它们。
是否有另外一种方法呢?例如:

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


解决方案

您可以使用

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

恰好如此 Convert.ToString 具有重载与适当的签名。



int.ToString 是它的重载都没有适当的签名(它们不包含 int 参数,因为它是隐含的)。在这种情况下,除了定义一个适配器函数之外,没有什么可以做的。


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);

解决方案

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.

这篇关于使用Func在函数中实现泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆