c# - 在调用新操作时帮助理解 C# 语法

标签 c# action invoke

我是 c# 新手,不了解调用新操作的语法,甚至不了解操作是什么。根据我对 Port1_DataReceived 的理解,我必须创建一个 Action ,因为我处于一个新的阶段......任何人都可以详细说明为什么我需要这样做吗?

public Form1()
{
    InitializeComponent();
    SerialPort Port1 = new SerialPort("COM11", 57600, Parity.None, 8, StopBits.One);
    Port1.DataReceived += new SerialDataReceivedEventHandler(Port1_DataReceived);
    Port1.Open();
}


private void Port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
     SerialPort Port = (SerialPort)sender;
     string Line = "";
     int BytestoRead = Port.BytesToRead;
     Line = Port.ReadLine();
     label1.Invoke(new Action(() =>
     {
          label1.Text = Line;
      }));
}

我真正难以理解的代码片段是:

label1.Invoke(new Action(() =>
         {
              label1.Text = Line;
          }));

有人能分解一下这是在做什么吗..我相信这没什么复杂的,只是我以前从未见过这样的事情。真正阻碍我的语法是 ()=> 新操作指向下面的代码或其他东西?

最佳答案

这使用一种称为“lambda 表达式”的东西来创建一个与 Action 构造函数期望的签名相匹配的匿名委托(delegate)。

你可以像这样达到同样的效果:

label1.Invoke(SetText);
...
public void SetText() { label1.Text = Line; }

或者像这样:

label1.Invoke(new Action(SetText));
...
public void SetText() { label1.Text = Line; }

或者像这样:

label1.Invoke(new Action(delegate() { label1.Text = Line; }));

或者像这样:

label1.Invoke(delegate() { label1.Text = Line; });

或者像这样:

label1.Invoke(() => label1.Text = Line);

这些大多只是语法快捷方式,可以更轻松地表示一个 Action 。

请注意,lambda 表达式通常带有参数。当只有一个参数时,括号是可选的:

list.ToDictionary(i => i.Key);

当没有参数或有多个参数时,括号是必要的,以明确你在做什么。因此,() =>

关于c# - 在调用新操作时帮助理解 C# 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6614157/

相关文章:

mysql - 其他查询执行 - Mysql

c# - 通用类型 : There is no implicit reference conversion from ToolStripStatusLabel to Control

java - 如何在struts2.xml文件中声明Generics Action?

C# 等待 MethodInvoker 完成

c# - 在 C# 中以结构作为返回值调用 C 函数

c# - 有没有办法检查 Ektron 是否在我的代码隐藏中以编辑模式加载页面? (C#)

c# - 确定是绝对还是相对 URL

c# - 在 C# 中根据引用的 XSD 验证 XML

c# - 用户代码未处理常规转换 InvalidOperationException

action - 创建一个带有 2 个操作页面的 html 表单