gpt4 book ai didi

c# - 在 C# 中,我如何创建一个扩展方法,该方法采用带有泛型参数 Func 作为参数的 lambda。

转载 作者:行者123 更新时间:2023-11-30 15:16:10 28 4
gpt4 key购买 nike

我正在尝试创建一个将 Func 作为参数的扩展方法,但出现错误。这是我得到的:

public static class MyExtensions
{
public static TResult ModifyString<T, TResult>(this string s, Func<T, TResult> f)
{
return f(s);
}
}

return f(s); 行我得到一个错误:Error CS1503 Argument 1: cannot convert from 'string' to 'T'

如何指定具有通用参数 T 和通用返回类型 TResult 的通用 lambda Func?

最佳答案

作为the other answer and comments suggest ,你已经知道参数类型T,所以你只需要指定TResult:

public static TResult ModifyString<TResult>(this string s, Func<string, TResult> f)
{
return f(s);
}

或始终通过 T:

public static TResult Modify<T, TResult>(this T s, Func<T, TResult> f)
{
return f(s);
}

关于c# - 在 C# 中,我如何创建一个扩展方法,该方法采用带有泛型参数 Func<T, TResult> 作为参数的 lambda。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50418807/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com