gpt4 book ai didi

c# - 函数引用与 Action 有何不同

转载 作者:行者123 更新时间:2023-11-30 19:59:50 27 4
gpt4 key购买 nike

我昨天遇到了这种情况,它一直在折磨着我。当编译器调用一个 Action 时,编译器不会提示为我的 DoThis 方法使用对函数的引用,据我所知,该 Action 是具有“void”返回类型的委托(delegate)。

DoThis 函数中的这个 Action 参数到底发生了什么?

public class testit
{
// Call DoThis with just a function reference. Should not work, but does.
public void DoThisThing1() {
DoThis(this.thing1);
}

// Call DoThis with an action. This is correct.
public void DoThisThing2() {
DoThis(new Action<string, string>(this.thing2));
}

private void DoThis(Action<string, string> thing)
{
// Do some common things here.

// Invoke Action
thing.Invoke("1", "2");

// Do other things.
}

private void thing1(string p1, string p2){}

private void thing2(string p1, string p2){}
}

最佳答案

如果您的问题是为什么这样做:

DoThis(this.thing1);

那么就是隐含的:

DoThis(new Action<string,string>(this.thing1));

(其中委托(delegate)类型是从 DoThis 的解析方法签名中推断出来的)

简单地说:编译器为我们填充了一些东西 - 自 C# 2 以来就存在的语法糖。在 C# 1.1 中,它不会编译。

关于c# - 函数引用与 Action<T> 有何不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22712476/

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