我有一个关注静态函数:
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在函数中实现泛型
发布评论