this.Foo(); 但我不知道“s”和“e”是什么?对于这行代码,我应该在 C# 中研究什么主题? 最佳答-6ren">
gpt4 book ai didi

c# - C# 代码语法中的 "s"和 "e"是什么

转载 作者:太空狗 更新时间:2023-10-29 22:04:29 25 4
gpt4 key购买 nike

我看到一些这样的代码:

textBox.TextChanged += (s, e) => this.Foo();

但我不知道“s”和“e”是什么?对于这行代码,我应该在 C# 中研究什么主题?

最佳答案

它们是 lambda 函数的参数。

编译器从上下文中推断出它们的类型,但允许编写更长(信息量更大)的形式:

 textBox.TextChanged += (object s, EventArgs e) => { this.Foo(); };

在这种表示法中,更容易看出它们是方法参数。
=> 的另一边是方法体。


回应评论:

Now is there a way to also rewrite the same lambda expression I have in a simpler C# syntax?

是的,您始终可以使用经典表示法。虽然这可能不会“更好”或什至“更简单”,但当您学习它时会更容易理解。

// The setup method
void MyMethod()
{
//textBox.TextChanged += new Eventhandler(MyTextChangedHandler); // C#1 and later
textBox.TextChanged += MyTextChangedHandler; // C#2 and later
}

// The subscribed method. The lambda is an inline version of this.
private void MyTextChangedHandler(object s, EventArgs e)
{
this.Foo();
}

关于c# - C# 代码语法中的 "s"和 "e"是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12533035/

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