【问题标题】:How to use Func when you require access to its parameter at invoke?当您需要在调用时访问其参数时如何使用 Func?
【发布时间】:2019-06-10 11:47:53
【问题描述】:

我有一个字典,其中包含一个字符串作为键,以及一个在发现所述字符串时运行的函数。然后它传入发现的使用的对象。我只想在函数体内访问这个对象,但不确定如何去做。我认为必须使用 lambda 运算符,但我真的不知道如何正确使用它。

public Dictionary<string, Func<object, bool>> stringReceivedRegister;

我的设置

string received_name = StringFormater.GetName(receivedMessage);

object changed_string = openMethod.Invoke(instance, new object[] { receivedMessage });
StringTypes.Instance.stringReceivedRegister[received_name].Invoke(changed_string);

当向 stringReceivedRegister 添加一个函数时,我将如何在我传入的函数中访问它?

StringTypes.Instance.stringReceivedRegister.Add("Test", function where i can get access to 'changed string');

【问题讨论】:

  • 不太清楚你在做什么,但是......假设你有一个签名为bool Foo(object input)的函数,那么它就像.Add("Test", Foo)一样简单

标签: c# function delegates


【解决方案1】:

要将函数添加到stringReceivedRegister,首先需要声明一个方法:

private static bool MyFunction(object x) {
    // ...
}

然后你可以将MyFunction 传递给Add

// Note the absence of () after "MyFunction". I am not actually calling it
stringReceivedRegister.Add("Test", MyFunction);

当您执行此操作时,x 参数将引用 changed_string

StringTypes.Instance.stringReceivedRegister[received_name].Invoke(changed_string);

必须非常时间声明一个方法很烦人,因此 C# 3 提供了 lambda 表达式,允许您这样做:

stringReceivedRegister.Add("Test", x => {
    // ...
});

同样,当您使用 changed_string 调用委托时,x 将引用 changed_string

【讨论】:

    【解决方案2】:

    看看这段代码:

    static bool FunctionTest(object o) {
    return true;
    }
    static void Main(string[] args) {
    Dictionary<string, Func<object, bool>> dict = new Dictonary<string, Func<object, bool>>();
    dict.Add("A", ((obj) => { return false; }));
    dict.Add("B", FunctionTest);
    
    Console.WriteLine(dict["A"](1));
    Console.WriteLine(dict["B"](1));
    

    【讨论】:

    • 如果你不确定,那你怎么回答这个问题呢?
    • @DavidG - 如果他想知道如何将函数作为值存储在字典中,那么我以正确的方式发布。 99% 是他的目标
    • 好的,所以您已经删除了“我不确定”这很好的文字,但现在您只是说“看看这段代码”,这是多余的文字。所以现在你有一个答案,它是一个没有解释的代码转储。有关信息,这不是我的反对意见,我只是想帮助您写出更好的答案。
    猜你喜欢
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多