帮助与理解C#语法,同时调用一个新的Action [英] Help with understanding C# syntax while Invoking a new Action

查看:169
本文介绍了帮助与理解C#语法,同时调用一个新的Action的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C#和不了解调用新的动作,甚至一个动作是什么样的语法。从我的理解Port1_DataReceived,我要创建一个动作,因为我是在一个新的胎面......任何人都可以对我为什么要做这个解释一下?

I am new to c# and do not understand the syntax of invoking a new action or even what an action is. From my understanding in Port1_DataReceived, I have to create an action because I am in a new tread... Can anyone elaborate on why I need to do this?

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;
      }));
}



中的代码剪断,我真的有麻烦的理解是:

The code snip that I am really having trouble understanding is:

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



有人能打破这个是什么做的,我确定它是没什么复杂的,只是我从来没有见过这样的事情。这是真正抱着我的语法是()=> 新动作指向下面的代码什么的?

Can someone break down what this is doing.. I am sure it is nothing to complicated, just that I have never seen anything like it before. The syntax that is really holding me up is ()=> the new action is pointing to the code below or something??

推荐答案

这使用了一种名为lambda表达式创建的行动构造预期签名匹配匿名委托。

This uses something known as a "lambda expression" to create an anonymous delegate that matches the signature expected by the Action constructor.

您能够达到这样的效果相同:

You could achieve the same effect like this:

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);



这些大多只是语法快捷方式,以方便代表一个动作。

These are mostly just syntactic shortcuts to make it easier to represent an action.

需要注意的是lambda表达式经常有参数。当只有一个参数,括号是可选的:

Note that lambda expressions often have parameters. When there is only one parameter, the parentheses are optional:

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

在没有参数或多个参数,括号是必需的,使其明显的你在做什么这样做。因此,()=方式>

When there are no parameters or multiple parameters, the parentheses are necessary to make it obvious what you're doing. Hence, the () =>.

这篇关于帮助与理解C#语法,同时调用一个新的Action的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆