这里正确的C#lambda语法是什么?

时间:2009-03-16 10:22:42

标签: c# lambda

我正在尝试使用lambda语法在运行时交换搜索规则引擎。

在下面的示例中,我需要什么语法,以便能够将方法的名称传递给我的GetSearchResults方法,以便GetSearchResults方法可以使用适当的逻辑来决定返回哪些结果?

string searchRulesMethodName = "SearchRules1(entry)";
var results = GetSearchResults(p => searchRulesMethodName);

以下是完整的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestLambda2
{
    class Program
    {
        static void Main(string[] args)
        {
            string searchRulesMethodName = "SearchRules1(entry)";
            var results = GetSearchResults(p => searchRulesMethodName);
            foreach (string entry in results)
            {
                Console.WriteLine(entry);
            }
            Console.ReadLine();
        }

        //only returns some entries
        public static bool SearchRules1(string entry)
        {
            if (entry == "one" || entry == "two") return true;
            return false;
        }

        //returns all entries
        public static bool SearchRules2(string entry)
        {
            return true;
        }

        public static List<string> GetSearchResults(Predicate<string> p)
        {
            string[] allEntries = { "one", "two", "three", "four", "five", "six", "seven" };
            List<string> results = new List<string>();
            foreach (string entry in allEntries)
            {
                if (p.Invoke(entry))
                {
                    results.Add(entry);
                }
            }
            return results;
        }

    }
}

解答:

感谢Marc,这正是我想要做的。使用反射也解决了“我如何告诉它属性签名”的问题:

static void Main(string[] args)
{
    string searchRulesMethodName = "SearchRules2";
    Predicate<string> predicate = (Predicate<string>) Delegate.CreateDelegate(typeof(Predicate<string>),
        typeof(Program).GetMethod(searchRulesMethodName));
    var results = GetSearchResults(predicate);

    foreach (string entry in results)
    {
        Console.WriteLine(entry);
    }
    Console.ReadLine();
}

1 个答案:

答案 0 :(得分:5)

要使用字符串,您必须使用反射来获取委托;

string searchRulesMethodName = "SearchRules1";
Predicate<string> predicate = (Predicate<string>)
    Delegate.CreateDelegate(typeof(Predicate<string>),
        typeof(Program).GetMethod(searchRulesMethodName));
var results = GetSearchResults(predicate);

当然,如果你在编译时知道所有选项,那么switch会更快更安全!

Predicate<string> predicate;
switch (searchRulesMethodName) {
    case "SearchRules1": predicate = SearchRules1; break;
    case "SearchRules2": predicate = SearchRules2; break;
    default: throw new InvalidOperationException("Unknown filter: "
        + searchRulesMethodName);
}
var results = GetSearchResults(predicate);