首页 > 解决方案 > 自定义无法运行的地方

问题描述

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>'

而且我不知道如何解决它。请查看我的代码。

标签: c#.netlinqdelegates

解决方案


您不能将 的实例强制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);

推荐阅读