什么=>从字段或方法指向的操作符是什么意思? C# [英] What does => operator pointing from field or a method mean? C#

查看:114
本文介绍了什么=>从字段或方法指向的操作符是什么意思? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的例子中看到了operator =>:

  public int Calculate(int x)=> ; DoSomething的(X); 

  public void DoSoething()=> SomeOtherMethod(); 

我从来没有见过这样的操作符,除了在lamba表达式中使用之外。
$ b

以下内容做了什么?在哪里使用?

解决方案

这些是使用C#6引入的Expression Body语句。重点在于使用lambda-像单行简单的属性和方法的语法。上面的语句扩展如下:

  public int Calculate(int x)
{
return DoSomething(x );
}

public void DoSoething()
{
SomeOtherMethod();
}

值得注意的是,属性还接受表达式体来创建简单的只读属性:

  public int Random => 5; 

相当于

  public int Random 
{
get
{
return 5;
}
}


I've seen an operator => used in the following example:

public int Calculate(int x) => DoSomething(x);

or

public void DoSoething() => SomeOtherMethod();

I have never seen this operator used like this before except in lamba expressions.

What does the following do? Where, when should this be used?

解决方案

These are Expression Body statements, introduced with C# 6. The point is using lambda-like syntax to single-line simple properties and methods. The above statements expand thusly;

public int Calculate(int x)
{
    return DoSomething(x);
}

public void DoSoething()
{
    SomeOtherMethod();
}

Notably, properties also accept expression bodies in order to create simple get-only properties:

public int Random => 5;

Is equivalent to

public int Random
{
    get
    {
        return 5;
    }
}

这篇关于什么=>从字段或方法指向的操作符是什么意思? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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