c# - 自定义无法运行的地方
问题描述
class Program
{
private delegate Boolean SomeDelegate(string value);
static void Main(string[] args)
{
var data = new List<string>() { "bill", "david", "john", "daviddd" };
SomeDelegate AA = A;
var test2 = data.DoWhere(AA); //This Line Compile is wrong
}
public static bool A(string value)
{
if (value.StartsWith("d"))
{
return true;
}
return false;
}
}
public static class CustomClass
{
public static IEnumerable<T> DoWhere<T>(this IEnumerable<T> source, Func<T, Boolean> predicate)
{
foreach (T item in source)
{
if (predicate.Invoke(item))
{
yield return item;
}
}
}
}
我想自定义方法和条件我需要什么数据。但是这段代码编译是错误的var test2 = data.DoWhere(AA);
无法从“SomeDelegate”转换为
'System.Func<string, bool>'
而且我不知道如何解决它。请查看我的代码。
解决方案
您不能将 的实例强制SomeDelegate
转换为 a Func<string, bool>
:
var test2 = data.DoWhere(AA); //This Line Compile is wrong
试试这个:
var test2 = data.DoWhere(c => AA(c));
或使用Invoke
:
var test2 = data.DoWhere(AA.Invoke);
或使用具有相同签名的方法,例如A
:
var test2 = data.DoWhere(A);
推荐阅读
- json - “[Shelter] 类型的值没有成员 'name'”
- java - 带有 AsyncHttpClient 的 JSON 请求
- wordpress - wordpress 的 PDF“InvalidPDFException:无效的 PDF 结构”错误?
- javascript - 如何缩短代码或将其存储在数据文件中
- git - npm-debug.log 在 .gitignore 文件中,但我仍然收到消息“没有添加到提交但存在未跟踪的文件(使用“git add”来跟踪)”
- lotus-notes - 如果在 Web 中不想要查看,则隐藏按钮 - Lotus Notes
- asynchronous - 如何从使用 Futures/async/await 的流中正确生成?
- android - 如何使用数据绑定和导航组件访问嵌套视图?
- php - 什么功能验证优惠券字段中的条目?(WooCommerce)
- scala - 在 Ubuntu 18.04 上找不到命令“scala”