使用Func在函数中实现泛型

编程入门 行业动态 更新时间:2024-10-05 01:20:58
本文介绍了使用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在函数中实现泛型

本文发布于:2023-11-26 23:24:17,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   Func

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!